2014-02-27 348 views
0

我有如下表:生成報告

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) 

我的目標是做一個彙報(新表),每代碼:

  • 對於那些代碼已經在狀態2和3,而日期在狀態2小於日期在狀態3和代碼在同一站點

對於上述表中的結果將是:

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 
    ---------- 

這是不是我想要的excatly因爲在這裏日期D9沒有與狀態3配對,以便該對的D9 < ...

希望這一切都有道理。

如果他們這樣做是否有SQL查詢來實現我的目的?

回答

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