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