让我们考虑这张表:

[name] [type]
"Ken Anderson" 1
"John Smith" 2
"Bill Anderson" 1
"George Anderson" 1
"Taylor Smith" 1
"Andrew Anderson" 2
"Dominic Smith" 2


然后该查询:

SELECT mates.type, COUNT(*) AS SmithsCount
FROM mates
WHERE mates.name LIKE "* Smith"
GROUP BY mates.type


结果应该像

[type] [SmithsCount]
1 1
2 2


如果我想在每个小组中也获得安德森计数,该怎么办?喜欢

[type] [SmithsCount] [AndersonsCount]
1 1 3
2 2 1


而且,当然,我希望这是最简单的;)我在SQL方面还很新,我阅读了有关W3 Schools和http://www.sql-tutorial.net/的教程,但是其中的示例基础很少,任何“更多”复杂的查询。有人有一些有用的链接吗?谢谢。

最佳答案

select type,
       sum(case when name like '% Smith' then 1 else 0 end) as SmithCount,
       sum(case when name like '% Anderson' then 1 else 0 end) as AndersonCount
    from mates
    group by type

10-07 19:48