2014-10-17 91 views
0

編寫一個sqlite查詢的最佳方法是在選擇不同的colA之後計算colC的出現次數?sqlite count of distinct occurences

SELECT colA, colB, colC FROM myTable WHERE colA IN ('121', '122','123','124','125','126','127','128','129'); 

通知ColA需要不同。

Example

雖然接近,這些結果是不正確的。

enter image description here

它應該返回:
123只貓1
124b中的狗1
125é蛇2
126f也魚1
127克蛇2

+0

UMM的第二個表包含了預期的效果? – Mihai 2014-10-17 20:35:42

+0

你如何選擇colB和colC? – 2014-10-17 20:39:07

+0

我用上面的select語句選擇它。 – adayzdone 2014-10-17 20:39:53

回答

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


查詢SQLite的3.8.3版本之前:

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 
+0

這將工作的SQLite? http://i.imgur.com/JkbMduF.png – adayzdone 2014-10-17 21:38:44

+0

這是有效的SQLite語法;請參閱https://www.sqlite.org/lang_with.html;使用[SQLite Manager](https://addons.mozilla)進行測試。org/en-US/firefox/addon/sqlite-manager /) – Rimas 2014-10-17 21:41:10

+0

看起來像使用舊的SQLite版本,因爲'WITH'子句是在3.8.3版本中引入的:http://www.sqlite.org/changes.html #version_3_8_3 – Rimas 2014-10-17 21:54:46

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見。

+0

與戈登相同的結果。 124應該有1計數,125和127應該有2計數。 http://i.imgur.com/Mc33MSq.png – adayzdone 2014-10-17 21:36:15

4

您可以通過colA聚合得到你最想要的:

select colA, count(*) 
from myTable 
where colA in ('121', '122','123','124','125','126','127','128','129') 
group by colA; 

它你是如何得到colBcolC還不清楚。您的示例數據了以下工作:

select colA, min(colB), max(colC), count(*) 
from myTable 
where colA in ('121', '122','123','124','125','126','127','128','129') 
group by colA; 
+0

嗨戈登。結果如下。 124應該有1計數,125和127應該有2計數。 http://i.imgur.com/dW39SL2.png – adayzdone 2014-10-17 21:33:29