串联日期时间记录

时间:2019-05-01 20:44:56

标签: sql-server

我有两个变量“ Patient_FIN”和“ Date_Time”。有一些重复的Patient_fin。我想将每个唯一的患者鳍连接成一行,同时还包括每个date_time变量。

 Example Data
 Financial Number     Requested 1 Date & Time
  1                2017-04-09 14:72:00.000
  1                2017-04-10 10:20:00.000
  2                2017-04-09 16:42:00.000
  3                2017-04-09 19:10:00.000
  4                2017-04-09 08:02:00.000
  4                2017-04-09 11:22:00.000

我希望输出看起来像这样:

Financial Number     Requested 1 Date & Time1  Requested 1 Date & Time2
         1            2017-04-09 14:72:00.000      2017-04-10 10:20:00.00
         2            2017-04-09 16:42:00.000
         3            2017-04-09 19:10:00.000
         4            2017-04-09 08:02:00.000      2017-04-09 11:22:00.000

我尝试使用以下代码,但是当有重复的FINS时,它将date_time放在一栏中。

 SELECT [Financial Number], [Requested 1 Date & Time] =
    STUFF((SELECT DISTINCT '   '  +[Requested 1 Date & Time]
         FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] b 
         WHERE b.[Financial Number] = a.[Financial Number] 
         FOR XML PATH('')), 1, 2, '')
 FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] a
 Group BY [Financial Number]

2 个答案:

答案 0 :(得分:1)

假设最大行数为4(并且“时间” 14:72是一个印刷错误),则可以使用“交叉表”来实现:

WITH CTE AS(
    SELECT FinancialNumber,
           RequestedDateTime,
           ROW_NUMBER() OVER (PARTITION BY V.FinancialNumber ORDER BY RequestedDateTime) AS RN
    FROM (VALUES (1,CONVERT(datetime,'2017-04-09T14:22:00.000')),
                 (1,CONVERT(datetime,'2017-04-10T10:20:00.000')),
                 (2,CONVERT(datetime,'2017-04-09T16:42:00.000')),
                 (3,CONVERT(datetime,'2017-04-09T19:10:00.000')),
                 (4,CONVERT(datetime,'2017-04-09T08:02:00.000')),
                 (4,CONVERT(datetime,'2017-04-09T11:22:00.000'))) V(FinancialNumber,RequestedDateTime))
SELECT C.FinancialNumber,
       MAX(CASE RN WHEN 1 THEN RequestedDateTime END) AS RequestedDateTime1,
       MAX(CASE RN WHEN 2 THEN RequestedDateTime END) AS RequestedDateTime2,
       MAX(CASE RN WHEN 3 THEN RequestedDateTime END) AS RequestedDateTime3,
       MAX(CASE RN WHEN 4 THEN RequestedDateTime END) AS RequestedDateTime4
FROM CTE C
GROUP BY C.FinancialNumber;

答案 1 :(得分:1)

您可以将PIVOTROW_NUMBER结合使用以下解决方案:

SELECT fin, [1], [2], [3], [4]
FROM (
    SELECT fin, date_col, ROW_NUMBER() OVER (PARTITION BY fin ORDER BY fin, date_col) AS rn
    FROM test
) st PIVOT (  
    MAX(date_col)
    FOR rn IN ([1], [2], [3], [4])  
) AS pt;

demo on dbfiddle.uk

注意:该解决方案支持一个财务编号,最多包含四个日期值。如果要为每个财务号支持更多日期值,则必须在[5], [6], ...SELECT上添加更多列(PIVOT)。