如何获取表中行的小计计数?

时间:2017-10-31 10:02:07

标签: sql sqlite group-by count

我有这个SQL查询吗?

SELECT COUNT(*) FROM PHRASE WHERE JLPT = 1
SELECT COUNT(*) FROM PHRASE WHERE JLPT = 2
SELECT COUNT(*) FROM PHRASE WHERE JLPT = 3
SELECT COUNT(*) FROM PHRASE WHERE JLPT = 4

有没有办法可以将这些查询合并为1,以便计算出有多少JLPT行的值为1,2,3& 4?

2 个答案:

答案 0 :(得分:5)

SELECT JLPT,
       COUNT(*)
FROM PHRASE
WHERE JLPT IN (1, 2, 3, 4)
GROUP BY JLPT;

答案 1 :(得分:2)

如果您希望将这些值放在一行中,请使用条件聚合。

SELECT
    COUNT(CASE WHEN JLPT = 1 THEN 1 END) JLPT1,
    COUNT(CASE WHEN JLPT = 2 THEN 1 END) JLPT2,
    COUNT(CASE WHEN JLPT = 3 THEN 1 END) JLPT3,
    COUNT(CASE WHEN JLPT = 4 THEN 1 END) JLPT4
FROM PHRASE