从概念上讲,我有一个包含水果项目列表的表格。我想在一个查询中查看有多少苹果,橙子,“苹果或橙子”以及“其他水果”的数量。
如何在T-SQL中实现这一目标?
答案 0 :(得分:9)
SELECT
COUNT(*) AS Allfruits,
COUNT(CASE WHEN fruit = 'Apple' THEN 1 END) AS AppleCount,
COUNT(CASE WHEN fruit = 'Orange' THEN 1 END) AS OrangeCount,
COUNT(CASE WHEN fruit IN ('Apple','Orange') THEN 1 END) AS AppleOrOrangeCount,
COUNT(*) - COUNT(CASE WHEN fruit IN ('Apple','Orange') THEN 1 END) AS OtherFruitCount
FROM
MyTable
注意:CASE在没有ELSE子句或某些显式条件的情况下给出NULL。 COUNT忽略NULL。