使用 case 语句汇总数据

Rolling up data with case statement

我正在使用 case 语句,但得到了多个用 NULL 填充的值。我怎么把它卷起来?我一定要疯了,因为这看起来太简单了,不可能这么复杂...

创建 table:

CREATE TABLE MedQuantity (
    PatName varchar(1),
    Contact# int,
    MedID int,
    MedQty int,
    EntryDate date);


INSERT INTO MedQuantity(PatName, Contact#,MedID,MedQty, EntryDate)
VALUES ('RODI, FEZ', 7, NULL, NULL, '2021-07-01'),
('RODI, FEZ',5, 32324, 185, NULL),
('RODI, FEZ',5, 4081, 15, NULL),
('RODI, FEZ',5, 4081, 50, NULL)

输出如下:

Name       Contact# MedID   MedQty  EntryDate
RODI, FEZ   7       NULL    NULL    2021-07-01 08:40:00
RODI, FEZ   5       32324   185     NULL
RODI, FEZ   5       4081    15      NULL
RODI, FEZ   5       4081    50      NULL

下面是我的查询:

    SELECT 
    
    [PatName]
    ,[Medication ID] = MAX(CASE WHEN T1.[Contact#] = 5 THEN T1.[MedID] end)
,[Medication Qty] = max(CASE WHEN T1.[Contact#] = 5 THEN T1.[MedQty] end)
,[Entry Date] = MAX(CASE WHEN T1.[Contact#] = 7 THEN T1.[EntryDate] end)
    
     FROM MedQuantity T1
    
      group by 
      T1.[PatName]

结果如下:

Name         Medication ID  Medication Qty  Entry Date
RODI, FEZ   4081             50              2021-07-01 08:40:00

但是,我期待:

您的行之间的关系不清楚,但您似乎正在尝试获取 contact# = 7 的最新行。这样的事情应该有效

返回最近的行 WHERE Con​​tact# = 7

DROP TABLE IF EXISTS  #MedQuantity

CREATE TABLE #MedQuantity (
    ID INT IDENTITY(1,1),
    PatName varchar(100),
    Contact# int,
    MedID int,
    MedQty int,
    EntryDate datetime2(0));


INSERT INTO #MedQuantity(PatName, Contact#,MedID,MedQty, EntryDate)
VALUES ('RODI, FEZ', 7, NULL, NULL, '2021-07-01 08:40:00'),
('RODI, FEZ',5, 32324, 185, NULL),
('RODI, FEZ',5, 4081, 15, NULL),
('RODI, FEZ',5, 4081, 50, NULL)

SELECT
    A.ID
    ,A.PatName
    ,A.MedID
    ,A.MedQty
    ,B.EntryDate
FROM #MedQuantity AS A
OUTER APPLY (
        /*Goes back and finds last row where Contact# = 7 to return EntryDate*/
        SELECT TOP (1) EntryDate
        FROM #MedQuantity AS DTA
        WHERE DTA.Contact# = 7
        AND DTA.ID < A.ID
        ORDER BY ID DESC
) AS B
WHERE A.Contact# = 5

您可以尝试在子查询中使用聚合window函数,然后过滤您期望的条件。

SELECT *
FROM (
    SELECT  
        [PatName]
        ,MedID
        ,MedQty
        ,[Entry Date] = MAX(CASE WHEN T1.[Contact#] = 7 THEN T1.[EntryDate] end) OVER(PARTITION BY PatName)
    FROM MedQuantity T1
) t1
WHERE MedID IS NOT NULL AND MedQty IS NOT NULL

sqlfiddle