My query returns a table that looks like this (please note that I am posting a very simplified version of the output):
+-------+------+------+------+------+
| | 1 | 2 | 3 | 4 |
+-------+------+------+------+------+
| 14234 | 3 | null | null | null |
| 14234 | null | null | 32 | null |
| 33334 | 4 | null | null | 5 |
| 33334 | null | 3 | null | null |
+-------+------+------+------+------+
and i would like to reformat it to look like this:
+-------+---+------+------+------+
| | 1 | 2 | 3 | 4 |
+-------+---+------+------+------+
| 14234 | 3 | null | 32 | null |
| 33334 | 4 | 3 | null | 5 |
+-------+---+------+------+------+
as you can see the rows have been put together (condensed), i don’t know what the right terminology would be.
is there a quick way to do this with sql server?
here’s the original query:
;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
I will call the first column in your example data “fk”
This query aggregates the rows on the fk column. If you have more then one row with the same fk value and with a NOT NULL value in one of the columns MAX() will pick the largest value. Use SUM() instead to calculate the sum. Both will ignore NULL values. However, there will also be a warning about that fact.