将对应于MIN(日期)的行操作为默认值

时间:2016-12-02 23:26:00

标签: sql-server sql-server-2012 group-by case

表T

+----+------------+----------+----------+----------+----+----+----+
| ID |   Sdate    |    Pr    |   Oxy    |   Met    | D1 | D2 | D3 |
+----+------------+----------+----------+----------+----+----+----+
|  1 | 7/14/2016  | Negative | Positive | Negative | N  | P  | N  |
|  1 | 8/10/2016  | Positive | Negative | Negative | P  | N  | N  |
|  1 | 9/23/2016  | Positive | Positive | Negative | P  | P  | N  |
|  2 | 6/17/2015  | Negative | Negative | Negative | N  | N  | N  |
|  2 | 8/1/2015   | Negative | Positive | Positive | N  | P  | P  |
|  2 | 11/19/2015 | Positive | Negative | Negative | P  | N  | N  |
|  3 | 2/28/2016  | Negative | Positive | Positive | N  | P  | P  |
|  3 | 4/3/2016   | Positive | Positive | Negative | P  | P  | N  |
+----+------------+----------+----------+----------+----+----+----+

我需要默认与每个组中最小日期对应的行,以显示D1,D2,D3 AS P的所有值,并将组中的剩余值设置为其他值

期望的输出:

+----+------------+----------+----------+----------+----+----+----+
| ID |   Sdate    |    Pr    |   Oxy    |   Met    | D1 | D2 | D3 |
+----+------------+----------+----------+----------+----+----+----+
|  1 | 7/14/2016  | Negative | Positive | Negative | P  | P  | P  |
|  1 | 8/10/2016  | Positive | Negative | Negative | P  | N  | N  |
|  1 | 9/23/2016  | Positive | Positive | Negative | P  | P  | N  |
|  2 | 6/17/2015  | Negative | Negative | Negative | P  | P  | P  |
|  2 | 8/1/2015   | Negative | Positive | Positive | N  | P  | P  |
|  2 | 11/19/2015 | Positive | Negative | Negative | P  | N  | N  |
|  3 | 2/28/2016  | Negative | Positive | Positive | P  | P  | P  |
|  3 | 4/3/2016   | Positive | Positive | Negative | P  | P  | N  |
+----+------------+----------+----------+----------+----+----+----+

代码尝试:

SELECT
    ID
    ,SDate
    ,CASE WHEN T.Pr = 'Positive' THEN 'P' ELSE 'N' END AS D1
    ,CASE WHEN T.Oxy = 'Positive' THEN 'P' ELSE 'N' END AS D2
    ,CASE WHEN T.Met = 'Positive' THEN 'P' ELSE 'N' END AS D3
FROM T

不确定如何将GROUP BY用于ID'然后将CASE嵌套为

CASE WHEN MIN(DATE) THEN 'P' ELSE CASE WHEN T.Pr...(and so on)

任何替代方法也将受到赞赏。感谢。

1 个答案:

答案 0 :(得分:1)

CREATE TABLE #TMP(ID INT
                    ,Sdate dATE
                    ,D1 CHAR(1)
                    ,D2 CHAR(1)
                    ,D3 CHAR(1)
                    )
INSERT INTO #TMP
VALUES
    (1,'20160714','N','P','N')
    ,(1,'20160810','P','N','N')
    ,(1,'20160923','P','P','N')
    ,(2,'20150617','N','N','N')
    ,(2,'20150801','N','P','P')
    ,(2,'20151119','P','N','N')
    ,(3,'20160228','N','P','P')
    ,(3,'20160403','P','P','N')

SELECT 
    A.ID
    ,A.Sdate
    ,CASE WHEN A.Sdate = C.Sdate THEN 'P' ELSE A.D1 END AS D1
    ,CASE WHEN A.Sdate = C.Sdate THEN 'P' ELSE A.D2 END AS D2
    ,CASE WHEN A.Sdate = C.Sdate THEN 'P' ELSE A.D3 END AS D3
FROM
    #TMP A
        CROSS APPLY (SELECT TOP 1 ID,SDate FROM #TMP B WHERE A.ID=B.ID ORDER BY Sdate ASC) C