在SQL中将行转换为列时缺少某些内容

时间:2016-01-14 20:59:47

标签: sql-server tsql

我正在尝试将行转换为表中的列,我能够获得结果集但是对于少数记录我错过了逻辑。下面是我正在运行的表和SQL,如果您对P123 PROCEDURE_END的查询结果应为NULL,而不是NULL,我将获得PROCEDURE_BEGIN值。我不确定我在这里缺少什么,请帮我解决这个问题。

INSERT  INTO #PAT_TEST
VALUES  ( 'P123', 'D457', '2015-11-29 01:48:00.000', 1 )
,       ( 'P123', 'D457', NULL, 0 )
,       ( 'P872', 'D457', '2015-11-30 02:48:00.000', 1 )
,       ( 'P872', 'D457', '2015-11-30 03:48:00.000', 0 );

SELECT  PAT_ID
      , DOC_ID
      , PROCEDURE_BEGIN = MIN(PROC_TIME)
      , PROCEDURE_END = MAX(PROC_TIME)
FROM    ( SELECT    PAT_ID
                  , DOC_ID
                  , PROC_TIME
                  , rn = ( ROW_NUMBER() OVER ( PARTITION BY PAT_ID, DOC_ID ORDER BY PROC_TIME ) - 1 ) / 2
          FROM      #PAT_TEST
        ) a
GROUP BY PAT_ID
      , DOC_ID
      , a.rn
ORDER BY PAT_ID
      , DOC_ID
      , PROCEDURE_BEGIN;

1 个答案:

答案 0 :(得分:0)

这对你有用吗?

如果应将null视为最大值:

SELECT PAT_ID ,DOC_ID, PROCEDURE_BEGIN=MIN(ISNULL(PROC_TIME,'99991231')), 
PROCEDURE_END=CASE WHEN MAX(ISNULL(PROC_TIME,'99991231')) ='99991231' THEN NULL ELSE MAX(ISNULL(PROC_TIME,'99991231')) END   
FROM( SELECT PAT_ID ,DOC_ID,PROC_TIME
,rn=(ROW_NUMBER() OVER (PARTITION BY PAT_ID,DOC_ID ORDER BY PROC_TIME)-1)/2
FROM #PAT_TEST
) a
GROUP BY PAT_ID ,DOC_ID, rn
ORDER BY PAT_ID,DOC_ID, PROCEDURE_BEGIN

enter image description here

如果应将null视为最小值:

    SELECT PAT_ID ,DOC_ID, PROCEDURE_BEGIN=CASE WHEN MIN(ISNULL(PROC_TIME,0)) = '19000101' THEN NULL ELSE MIN(ISNULL(PROC_TIME,0)) END, 
PROCEDURE_END=MAX(PROC_TIME )   
FROM( SELECT PAT_ID ,DOC_ID,PROC_TIME
,rn=(ROW_NUMBER() OVER (PARTITION BY PAT_ID,DOC_ID ORDER BY PROC_TIME)-1)/2
FROM #PAT_TEST
) a
GROUP BY PAT_ID ,DOC_ID, rn
ORDER BY PAT_ID,DOC_ID, PROCEDURE_BEGIN

enter image description here