我是SQL的新面孔。 假设我有一组数据:
http://www.red-gate.com/products/dotnet-development/reflector/
我希望得到这样的结果:
==================
|| iphone6 ||
|| iphone7 ||
|| iphone7s ||
|| Android 7.1 ||
|| Android 6.3 ||
==================
我的代码是这样的:
||Model ||Amount ||
==========================
||iphone || 3||
||Android || 2||
==========================
但我的输出是:
SELECT
CASE
WHEN model LIKE '%Android%' THEN 'Android'
WHEN model LIKE '%iPhone%' THEN 'IPhone'
END,
, COUNT(*) AS Amount FROM #table GROUP BY model;
我该如何解决?
答案 0 :(得分:4)
您只需要按照您要创建的列进行聚合:
SELECT (CASE WHEN model LIKE '%Android%' THEN 'Android'
WHEN model LIKE '%iPhone%' THEN 'IPhone'
END),
COUNT(*) AS Amount
FROM #table
GROUP BY (CASE WHEN model LIKE '%Android%' THEN 'Android'
WHEN model LIKE '%iPhone%' THEN 'IPhone'
END);