SQL Server Group Select in an Only row

owfi6suc  于 2024-01-05  发布在  其他
关注(0)|答案(1)|浏览(136)
SELECT 
    loadNumber, 
    CASE 
        WHEN E.Clave = 'LOD' THEN FechaEvento 
        ELSE NULL 
    END AS 'Load Date USA', 
    CASE 
        WHEN E.Clave = 'DAA' THEN FechaEvento 
        ELSE NULL 
    END AS 'Colocacion AA',
    CASE 
        WHEN E.CLAVE = 'RPD' THEN FechaEvento 
        ELSE NULL 
    END AS 'Docs Listos',
    CASE 
        WHEN E.Clave = 'IDT' THEN FechaEvento 
        ELSE NULL 
    END AS 'Llegada MX',
    CASE 
        WHEN E.Clave = 'ULD' THEN FechaEvento 
        ELSE NULL 
    END AS 'Descarga MX'
FROM
    OrdenEvento OE
INNER JOIN 
    Evento E ON OE.idEvento = E.ID
WHERE 
    loadNumber = '60317'
GROUP BY 
    loadNumber, e.Clave, FechaEvento

I have this SQL, trying to gather all in one single row. My goal if there is a number that match with the cases enter and if there is not a single row with full NULL Values, or only a few matches and others with Null Values

loadNumberLoad DateColocacion AADocs ListosLlegada MXDescarga MX
60317NULLNULLNULLNULLNULL
60317NULLNULLNULLNULLNULL
60317NULLNULLNULLNULLNULL
60317NULL2023-12-18 14:21:44.820NULLNULLNULL
60317NULLNULLNULLNULLNULL
60317NULLNULLNULL2023-12-18 14:28:52.877NULL
603172023-12-18 14:24:39.730NULLNULLNULLNULL
60317NULLNULLNULLNULLNULL
60317NULLNULLNULLNULLNULL
60317NULLNULLNULLNULLNULL
60317NULLNULL2023-12-18 14:28:02.197NULLNULL
60317NULLNULLNULLNULL2023-12-18 14:29:04.193

This is the current result and this is the wanted result

loadNumberLoad DateColocacion AADocs ListosLlegada MXDescarga MX
603172023-12-18 14:24:39.7302023-12-18 14:21:44.8202023-12-18 14:28:02.1972023-12-18 14:28:52.8772023-12-18 14:29:04.193
vc6uscn9

vc6uscn91#

You need some aggregation to collapse all those rows to one row per loadNumber.

That also means your GROUP BY should only be loadNumber.

SELECT
  loadNumber, 
  MAX(CASE WHEN E.Clave='LOD' THEN FechaEvento ELSE NULL END)   AS 'Load Date USA', 
  MAX(CASE WHEN E.Clave='DAA' THEN FechaEvento ELSE NULL END)   AS 'Colocacion AA',
  MAX(CASE WHEN E.CLAVE='RPD' THEN FechaEvento ELSE NULL END)   AS 'Docs Listos',
  MAX(CASE WHEN E.Clave='IDT' THEN FechaEvento ELSE NULL END)   AS 'Llegada MX',
  MAX(CASE WHEN E.Clave='ULD' THEN FechaEvento ELSE NULL END)   AS 'Descarga MX'
FROM
  OrdenEvento OE
INNER JOIN
  Evento E
    ON OE.idEvento=E.ID
WHERE
  loadNumber='60317'
GROUP BY
  loadNumber

相关问题