我现在搜索并尝试了很多,以便在运行此查询时弄清楚如何在表中替换名称“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仍然存在。
有什么想法吗?
答案 0 :(得分:1)
您可以这样做的一种方法是将查询包装在另一个选择中,然后将null
值替换为COALESCE
或CASE
表达式:
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
表达式,因为您要比较多个列。