SQL:使用Case When,Grouping_ID创建新列

时间:2019-01-25 08:22:07

标签: mysql

如何在使用CASE WHENGROUPING_ID()ROLLUP()语法的同时在SQL中创建一个全新的列?

到目前为止,我已经尝试过:

SELECT Country, ContactTitle, COUNT(ContactTitle) AS Count
,CASE(
WHEN
GROUPING_ID(Legend) = 0 THEN ' '
WHEN
GROUPING_ID(Legend) = 1 THEN 'SUBTOTAL(Country)')
GROUP BY ROLLUP(Country, ContactTitle)
FROM dbo.Customers

2 个答案:

答案 0 :(得分:0)

CASE需要一个END

在测试期间,您可以输出GROUPING_ID或GROUPING来了解它们返回的内容。

SELECT Country, ContactTitle, COUNT(*) AS Count,
 (CASE
  WHEN GROUPING_ID(Country, ContactTitle) = 1
  THEN CONCAT('SUBTOTAL(',Country,')')
  WHEN GROUPING(Country) = 1
  THEN 'TOTAL'
  ELSE ' '
  END) AS Legend
FROM Customers
GROUP BY Country, ContactTitle WITH ROLLUP;

答案 1 :(得分:0)

SELECT Country, ContactTitle, COUNT(ContactTitle) AS Count, 
CASE 
    WHEN GROUPING_ID(Country,ContactTitle) = 0 THEN ''
    WHEN GROUPING_ID(Country,ContactTitle) = 1 THEN CONCAT('Subtotal for ',Country)
END AS Legend
FROM dbo.Customers
GROUP BY ROLLUP(Country, ContactTitle);