How to count 2 different data in one query

一笑奈何 提交于 2019-12-04 05:57:51

Using a CASE statement lets you count whatever you want in a single query:

SELECT
    SUM(CASE WHEN Persons.Name = 'John' THEN 1 ELSE 0 END) AS JohnCount,
    SUM(CASE WHEN Persons.Name = 'John' AND Persons.Age > 30 THEN 1 ELSE 0 END) AS OldJohnsCount,
    COUNT(*) AS AllPersonsCount
FROM Persons

Use:

SELECT COUNT(p.id),
       SUM(CASE WHEN p.age > 30 THEN 1 ELSE 0 END)
  FROM PERSONS p
 WHERE p.name = 'John'

It's always preferable when accessing the same table more than once, to review for how it can be done in a single pass (SELECT statement). It won't always be possible.

Edit:

If you need to do other things in the query, see Chris Shaffer's answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!