0

我现在搜索并尝试了很多,以弄清楚如何在运行此查询时替换表中的名称“NULL”:

SELECT 
YEAR(orderdate) AS Years,
       (CASE WHEN country = 'US' THEN 'US' ELSE 'WORLD' END) AS region,
   SUM(netamount) AS TotSales
FROM orders o JOIN
     customers c 
     ON o.customerid = c.customerid
GROUP BY  (CASE WHEN country = 'US' THEN 'US' ELSE 'WORLD' END),YEAR(orderdate) WITH ROLLUP;

我得到这张表:http: //imgur.com/pzHa8fK

我想将 Null 分别替换为 'SubTotal' 和 'GrandTotal'。我试过了:

COALESCE(year(orderdate), 'Subtotal') years,...

和 'IFNULL(...)' 相同,但不是替换名称,而是创建一个额外的列,其中包含所有年份,并且 NULL 仍然保留。

任何的想法?

4

1 回答 1

1

您可以这样做的一种方法是将查询包装在另一个选择中,然后用 a或表达式替换null值:COALESCECASE

select 
    case 
        when Years is null and region is null then 'GrandTotal'
        when Years is null then 'SubTotal' 
        else Years end Years,
    coalesce(region, '') region,
    TotSales
from
(
    SELECT YEAR(orderdate) AS Years,
       (CASE WHEN country = 'US' THEN 'US' ELSE 'WORLD' END) AS region,
       SUM(netamount) AS TotSales
    FROM orders o JOIN
         customers c 
         ON o.customerid = c.customerid
    GROUP BY  (CASE WHEN country = 'US' THEN 'US' ELSE 'WORLD' END),YEAR(orderdate) WITH ROLLUP
) d

请注意,我使用的是CASE表达式,因为您要比较多个列。

请参阅带有演示的 SQL Fiddle

于 2013-04-02T17:40:36.237 回答