SQL - 如何将两个表交叉连接到重复值

时间:2017-07-27 00:37:57

标签: sql sql-server tsql join cross-join

我有两张看起来像这样的表:

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

2 个答案:

答案 0 :(得分:3)

您需要CROSS JOIN开启MonthEndDateCustomerId的所有组合。完成后,在LEFT JOIN上执行table2即可获得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 :(得分:0)

我想你只想要left join

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