2017-07-27 89 views
2

我有2个表看起来像这样:SQL - 如何交叉连接两个表中重复值

MonthEndDate 
2016-06-30 00:00:00.000 
2016-07-31 00:00:00.000 
2016-08-31 00:00:00.000 
2016-09-30 00:00:00.000 
2016-10-31 00:00:00.000 
2016-11-30 00:00:00.000 
2016-12-31 00:00:00.000 

MonthEndDate    CustomerId Flag 
2016-06-30 00:00:00.000 123   1 
2016-07-31 00:00:00.000 123   1 
2016-08-31 00:00:00.000 123   1 
2016-09-30 00:00:00.000 123   1 

我想输出看起来像这样:

MonthEndDate    CustomerId  Flag 
2016-06-30 00:00:00.000  123   1 
2016-07-31 00:00:00.000  123   1 
2016-08-31 00:00:00.000  123   1 
2016-09-30 00:00:00.000  123   1 
2016-10-31 00:00:00.000  123   0 
2016-11-30 00:00:00.000  123   0 
2016-12-31 00:00:00.000  123   0 

表1是一个DimDate表具有月份结束日期。


2是CustomerInfo表。
每位客户的Flag设置为1,只要该客户具有给定月末的值。
我想得到一个输出,将有每个月结束日期(这就是为什么我起诉DimDate表),当一个客户没有一个价值的月结束我希望国旗显示0.
我'中号使用SQL Server 2005

下面是我使用的一些示例代码:

DECLARE @table1 TABLE 
(
    MonthEndDate DATETIME 
) 

INSERT INTO @table1 
VALUES('2016-06-30 00:00:00.000') 

INSERT INTO @table1 
VALUES('2016-07-31 00:00:00.000') 
INSERT INTO @table1 
VALUES('2016-08-31 00:00:00.000') 
INSERT INTO @table1 
VALUES('2016-09-30 00:00:00.000') 
INSERT INTO @table1 
VALUES('2016-10-31 00:00:00.000') 
INSERT INTO @table1 
VALUES('2016-11-30 00:00:00.000') 
INSERT INTO @table1 
VALUES('2016-12-31 00:00:00.000') 

DECLARE @table2 TABLE 
(
    MonthEndDate DATETIME 
    ,CustomerId INT 
    ,Flag INT 
) 

INSERT INTO @table2 
VALUES('2016-06-30 00:00:00.000',123,1) 

INSERT INTO @table2 
VALUES('2016-07-31 00:00:00.000',123,1) 
INSERT INTO @table2 
VALUES('2016-08-31 00:00:00.000',123,1) 
INSERT INTO @table2 
VALUES('2016-09-30 00:00:00.000',123,1) 

SELECt * FROM @table1 


SELECt * FROM @table2 

回答

3

您需要做一个CROSS JOIN就可以得到MonthEndDateCustomerId的所有组合。当你有一个,做一个LEFT JOINtable2得到Flag

SELECT 
    t1.MonthEndDate, 
    c.CustomerId, 
    Flag = ISNULL(t2.Flag, 0) 
FROM @table1 t1 
CROSS JOIN (SELECT DISTINCT CustomerId FROM @table2) c 
LEFT JOIN @table2 t2 
    ON t1.MonthEndDate = t2.MonthEndDate 
    AND c.CustomerId = t2.CustomerId 
+1

出于某种原因,我从来没有想过要同时使用十字和左。每天学习新事物。 – jmich738

0

我觉得你只是想要一个left join

select t1.*, coalesce(t2.flag, 0) as flag 
from @table1 t1 left join 
    @table2 t2 
    on t1.MonthEndDate = t2.MonthEndDate; 
+0

不幸的是,这并不带回在客户 – jmich738