SQL Server - 将nulls替换为表中的名称

时间:2017-08-04 01:14:14

标签: sql-server

Data

我有下面的代码片段,我无法想象如何用表格中的产品名称替换NULL值,我使用了case语句但创建了一个额外的列,而不是我要找的结果:

数据集

Apparel  Brand    TotalPrice
-------  -----    ----------
Jeans    Charly      2249.85 
Jeans    Lee            0.00 
Jeans    Lee        10497.90 
Jeans    NULL       12747.75 
Shirt    Gucci      34539.90 
Shirt    Tommy H     1070.00 
Shirt    NULL       35609.90 
NULL     NULL       48357.65

查询

SELECT Apparel, Brand, SUM (COALESCE((Quantity * Price),0)) AS TotalPrice
FROM #Sales
GROUP BY ROLLUP (Apparel, Brand)

期望的结果

Apparel Brand                     TotalPrice
Jeans   Charly                       2249.85
Jeans   Lee                             0.00
Jeans   Lee                         10497.90
Jeans   **SubToTal jeans**          12747.75
Shirt   Gucci                       34539.90
Shirt   Tommy H                      1070.00
Shirt   **SubToTal Shirts**         35609.90
**Grand Total** **Grand Total**     48357.65

任何帮助都将非常感谢

提前致谢

1 个答案:

答案 0 :(得分:1)

SELECT ISNULL(Apparel, '**Grand Total**') as Apparel, 
    ISNULL(Brand, CASE WHEN apparel IS NULL THEN '**Grand Total**' ELSE '**Subtotal ' + apparel + '**' END) as Brand, 
    SUM (COALESCE((Quantity * Price),0)) AS TotalPrice
FROM #Sales
GROUP BY ROLLUP (Apparel, Brand)

使用样本数据输出:

Apparel         Brand               TotalPrice
pants           gucci               11000.00
pants           tommy               15000.00
pants           **Subtotal pants**  26000.00
shirt           gucci               3000.00
shirt           tommy               7000.00
shirt           **Subtotal shirt**  10000.00
**Grand Total** **Grand Total**     36000.00

以下是我的示例数据,如果您想尝试一下:

declare @t table (apparel varchar(100), brand varchar(100), Quantity int, Price numeric(12,2))
insert into @t values ('shirt', 'gucci', 10, 100)
insert into @t values ('shirt', 'gucci', 10, 200)
insert into @t values ('shirt', 'tommy', 10, 300)
insert into @t values ('shirt', 'tommy', 10, 400)
insert into @t values ('pants', 'gucci', 10, 500)
insert into @t values ('pants', 'gucci', 10, 600)
insert into @t values ('pants', 'tommy', 10, 700)
insert into @t values ('pants', 'tommy', 10, 800)