编写一个sqlite查询的最佳方法是在选择不同的colA&#39之后计算colC的出现次数?
SELECT colA, colB, colC FROM myTable WHERE colA IN ('121', '122','123','124','125','126','127','128','129');
注意ColA需要与众不同。
虽然很接近,但这些结果不正确。
它应该返回:
123一只猫1
124 b狗1
125 e蛇2
126 f鱼1
127克蛇2
答案 0 :(得分:4)
您可以按colA
汇总以获得您想要的大部分内容:
select colA, count(*)
from myTable
where colA in ('121', '122','123','124','125','126','127','128','129')
group by colA;
目前还不清楚您是如何获得colB
和colC
的。以下适用于您的示例数据:
select colA, min(colB), max(colC), count(*)
from myTable
where colA in ('121', '122','123','124','125','126','127','128','129')
group by colA;
答案 1 :(得分:2)
WITH t AS (
SELECT colA, min(colB) AS colB, max(colC) AS colC
FROM myTable
WHERE colA IN ('121', '122','123','124','125','126','127','128','129')
GROUP BY colA
)
SELECT t.*, c.colC_count
FROM t
JOIN (
SELECT colC, count(*) AS colC_count
FROM t
GROUP BY colC
) c ON c.colC = t.colC
说明:
第一个子查询(在WITH
内)获得所需的结果,但没有计数列。第二个子查询(在JOIN
内)计算所需结果中的每个colC
值重复,并将此计数返回到最终结果。
由于第一个子查询在两个地方使用,因此非常有用的WITH
子句。更多信息:https://www.sqlite.org/lang_with.html
在版本3.8.3之前查询SQLite:
SELECT t.*, c.colC_count
FROM (
SELECT colA, min(colB) AS colB, max(colC) AS colC
FROM myTable
WHERE colA IN ('121', '122','123','124','125','126','127','128','129')
GROUP BY colA
) t
JOIN (
SELECT colC, count(*) AS colC_count
FROM (
SELECT max(colC) AS colC
FROM myTable
WHERE colA IN ('121', '122','123','124','125','126','127','128','129')
GROUP BY colA
) c
GROUP BY colC
) c ON c.colC = t.colC
答案 2 :(得分:1)
我认为您正在寻找COUNT(colC) + GROUP BY (colA)的组合。像这样:
SELECT colA, colB, colC, COUNT(colC)
FROM myTable
WHERE colA IN ('121', '122','123','124','125','126','127','128','129')
GROUP BY (colA);
另见this Q&A。