我有下表:
Code State Site Date
----------
x1 2 s1 d1
x2 2 s1 d2
x3 2 s1 d3
x1 3 s2 d4
x2 3 s1 d5
x3 3 s1 d6
x4 2 s2 d7
x5 2 s2 d8
x3 2 s1 d9
----------
(here d1<d2....<d7)
我的目标是为每个代码制作一份报告(新表):
对于上表,结果将是:
Code Date
----------
x2 d2
x3 d3
x2 d5
x3 d6
----------
我尝试的是:
Select Code,Date,Site from Transactions where State='2' and Site in
(Select Site from Transactions where State='3')
但是这个查询还不够,因为对于给定的表,它返回:
Code Date
----------
x2 d2
x3 d3
x2 d5
x3 d6
x3 d9
----------
这不是我想要的,因为在这里,日期d9没有与状态3配对,因此d9&lt;那对......
希望这一切都有意义。
如果他们这样做是否有SQL查询来实现我的目的?
答案 0 :(得分:2)
对于你给出的这个套装应该有用,虽然因为你没有提到特定状态的多个日期会发生什么,所以我没有回答这个问题。 很长但是有效
declare @WhatEverYourTableNameIs Table
(
Code varchar(2),
State int,
Site VarChar(2),
DateGotten Date
)
Insert into @WhatEverYourTableNameIs
Values
('x1',2,'s1','2014-1-1'),
('x2',2,'s1','2014-1-2'),
('x3',2,'s1','2014-1-3'),
('x1',3,'s2','2014-1-4'),
('x2',3,'s1','2014-1-5'),
('x3',3,'s1','2014-1-6'),
('x4',2,'s2','2014-1-7'),
('x5',2,'s2','2014-1-8'),
('x3',2,'s1','2014-1-9')
SELECT * into #MyTemp
FROM
(
SELECT Code, [State],Site [Site],DateGotten
FROM @WhatEverYourTableNameIs
GROUP BY Code, [State], Site, DateGotten
) a
SELECT *
FROM
(
SELECT DISTINCT a.Code, a.State, a.Site, a.DateGotten
FROM #MyTemp a
JOIN (
SELECT *
FROM #MyTemp
WHERE [State] =3
) b ON a.Code = b.Code and a.Site = b.Site
WHERE a.[State] = 2 and a.DateGotten < b.DateGotten
UNION
SELECT DISTINCT b.Code, b.State, b.Site, b.DateGotten
FROM #MyTemp a
JOIN (
SELECT *
FROM #MyTemp
WHERE [State] =3
) b on a.Code = b.Code and a.Site = b.Site
WHERE b.[State] = 3 and a.DateGotten < b.DateGotten
) a
order by a.DateGotten
drop table #MyTemp
>Code State Site DateGotten >x2 2 s1 2014-01-02 >x3 2 s1 2014-01-03 >x2 3 s1 2014-01-05 >x3 3 s1 2014-01-06