2012-03-13 62 views
1

如何将给定查询的结果集存储在新表中。结果集的表别名

select d1.year,d1.month,d1.Circle_code,d1.Call_type_code,d1.DescId,d1.CustId, 
d1.call_logged,d2.Call_Cancel 
from dbo.Table_M_CALL_LOGGED as d1 
join dbo.Table_M_CALL_CANCEL as d2 on 

d1.year=d2.year 
and d1.month=d2.month 
and d1.Circle_Code=d2.Circle_Code 
and d1.Call_Type_Code=d2.Call_Type_Code 
and d1.DescId=d2.DescId 
and d1.CustId=d2.custID 
+0

由于您似乎是SQL的新手,很好的入门习惯是用更好的描述来命名您的别名(d1,d2)。 d1 => loggedCall,d2 => cancelledCall。既然你只键入了一次,但多次阅读,那么花一点时间细读一下是个好主意。长远来看,你会发现它效果更好。 – 2012-03-28 10:29:50

回答

5

我在这里创造新的临时表,只是你展示如何直接将查询结果为表....

--Creating new TempTable 
CREATE TABLE #tempTable(tempyear nvarchar(20),tempmonth nvarchar(20),Circle_code nvarchar(20),Call_type_code nvarchar(20), 
DescId nvarchar(20),CustId nvarchar(20),call_logged nvarchar(30),Call_Cancel nvarchar(20)); 

--Inserting the data into tempTable 
INSERT INTO #tempTable(tempyear,tempmonth,Circle_code,Call_type_code,DescId,CustId,call_logged,Call_Cancel) 
        select d1.year,d1.month,d1.Circle_code,d1.Call_type_code,d1.DescId,d1.CustId, 
        d1.call_logged,d2.Call_Cancel 
        from dbo.Table_M_CALL_LOGGED as d1 
        join dbo.Table_M_CALL_CANCEL as d2 on 
        d1.year=d2.year 
        and d1.month=d2.month 
        and d1.Circle_Code=d2.Circle_Code 
        and d1.Call_Type_Code=d2.Call_Type_Code 
        and d1.DescId=d2.DescId 
        and d1.CustId=d2.custID 

下面的方法时,不较早创建的表,需要使用将来自一个表的数据插入到另一个表中新创建的表中时创建。新表使用与选定列相同的数据类型创建。

    SELECT d1.year,d1.month,d1.Circle_code,d1.Call_type_code,d1.DescId,d1.CustId, 
        d1.call_logged,d2.Call_Cancel 
        INTO new_table --Here inserting into new table 
        FROM dbo.Table_M_CALL_LOGGED AS d1 
        join dbo.Table_M_CALL_CANCEL AS d2 ON 
        d1.year=d2.year 
        AND d1.month=d2.month 
        AND d1.Circle_Code=d2.Circle_Code 
        AND d1.Call_Type_Code=d2.Call_Type_Code 
        AND d1.DescId=d2.DescId 
        AND d1.CustId=d2.custID 
+0

有没有其他方法可以做到这一点..? – 2012-03-13 05:36:13

+0

是的,我会在我的答案更新另一种方法.... – 2012-03-13 05:42:46

+0

亚,其工作对我...感谢它。我只看这只 – 2012-03-13 05:59:32