2012-10-19 78 views
1

數據集我的查詢返回一個表,看起來像這樣(請注意,我張貼的輸出非常簡化的版本):冷凝在空

+-------+------+------+------+------+ 
|  | 1 | 2 | 3 | 4 | 
+-------+------+------+------+------+ 
| 14234 | 3 | null | null | null | 
| 14234 | null | null | 32 | null | 
| 33334 | 4 | null | null | 5 | 
| 33334 | null | 3 | null | null | 
+-------+------+------+------+------+ 

,我想重新格式化它看起來像這樣的:

+-------+---+------+------+------+ 
|  | 1 | 2 | 3 | 4 | 
+-------+---+------+------+------+ 
| 14234 | 3 | null | 32 | null | 
| 33334 | 4 | 3 | null | 5 | 
+-------+---+------+------+------+ 

,你可以看到行已被放在一起(濃縮),我不知道正確的術語是什麼。

有沒有一種快速的方法來做到這一點與SQL Server?

這裏的原始查詢:

;WITH 
PivotQuery as (
    select client_id, 
     [1],[2],[3],[4],[5],[6],[7] 
     from 
     ( SELECT DISTINCT CLIENT_ID 
     , PATIENT_ID 
     , count(*) over (partition by client_id, patient_id) AS patientcount 

     from f_accession_daily) as SourceTable 
     PIVOT 
     (
     count(patient_id) 
     for patientcount in ([1],[2],[3],[4],[5],[6],[7]) 
     ) as pivottable), 

MinMaxTimes as (
    SELECT a.client_id AS client_id 
    ,a.patientcount TimesTested 
     , count(a.patientcount)/a.patientcount AS count 
     , max(f.received_date) AS maxRecDate 
     , min(f.received_date) AS minRecDate 
    FROM 
    (
     SELECT DISTINCT CLIENT_ID 
     , PATIENT_ID 
     , count(*) over (partition by client_id, patient_id) AS patientcount 

     from f_accession_daily 

    ) AS a 
    JOIN F_ACCESSION_DAILY AS f ON a.CLIENT_ID = f.CLIENT_ID 
     AND a.PATIENT_ID = f.PATIENT_ID 

    GROUP BY a.CLIENT_ID, a.patientcount), 

maxDates as (
SELECT client_id, [1] maxdate1, [2] maxdate2, [3] maxdate3, [4] maxdate4, [5] maxdate5, [6] maxdate6, [7] maxdate7 
FROM MinMaxTimes t 
PIVOT (max(maxRecDate) 
for TimesTested IN ([1], [2], [3], [4], [5], [6], [7]) 
) as p), 

minDates as (
SELECT client_id, [1] mindate1, [2] mindate2, [3] mindate3, [4] mindate4, [5] mindate5, [6] mindate6, [7] mindate7 
FROM MinMaxTimes t 
PIVOT (max(minRecDate) 
for TimesTested IN ([1], [2], [3], [4], [5], [6], [7]) 
) as p) 

SELECT i.client_id, 
    p.[1], maxdate1, mindate1, 
    p.[2], maxdate2, mindate2, 
    p.[3], maxdate3, mindate3, 
    p.[4], maxdate4, mindate4, 
    p.[5], maxdate5, mindate5, 
    p.[6], maxdate6, mindate6, 
    p.[7], maxdate7, mindate7 
FROM PivotQuery p 
LEFT OUTER JOIN maxDates a ON p.client_id = a.client_id 
LEFT OUTER JOIN mindates i ON a.client_id = i.client_id 
+0

如果您發佈您現有的查詢,而不是讓我們訴諸假設,這將有所幫助。 – gilly3

+0

@ gilly3謝謝,我剛剛發佈了原始查詢 –

回答

4

我會打電話的第一列在您的示例數據「FK」

SELECT fk,MAX(Col1),MAX(Col2),MAX(Col3),MAX(Col4) 
FROM dbo.YourTable 
GROUP BY fk 

該查詢聚集在FK列的行。如果你有多個具有相同fk值的行,並且在其中一列中有NOT NULL值,那麼MAX()將選擇最大值。使用SUM()來計算總和。兩者都會忽略NULL值。但是,這個事實也會有警告。