我有一张表,我每周都会在其中插入一些记录。有一列日期。我想使用列键比较上周和本周的数据。下面是我的表:
Name Date Key
ABC 07 June 1
BAC 07 June 2
WSD 07 June 3
QWE 14 June 9
QWT 14 June 2
DEF 14 June 1
CXZ 14 June 6
我想要 6 月 14 日的数据,其中键与 6 月 7 日的数据相同。
期望的输出:
Name Date Key
QWT 14 June 2
DEF 14 June 1
我正在使用 CTE 加入,但我没有得到想要的结果。
;WITH T1
AS
(SELECT * FROM [Table] where [Date]= '07 June'),
T2
AS
(SELECT * FROM [Table] where [Date]= '14 June')
SELECT *
FROM T2
INNER JOIN T1 ON T1.[KEY] = T2.[KEY];
你所拥有的应该返回你所说的你想要的结果。我可能会将其简化为具有自联接的单个查询。像这样的东西。
select t2.*
from [Table] t
join [Table] t2 on t.MyKey = t2.MyKey
where t.MyDate = '07 June'
and t2.MyDate = '14 June'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句