簡體   English   中英

SQL使用if檢查多行並獲得計數

[英]SQL check multiple rows with if and get the count

表:

id  | name  | country
---------------------
1   | abc   | India
2   | abc   | America
3   | abc   | USA
4   | xyz   | India
5   | xyz   | America
6   | xyz   | USA

到目前為止,QUERY已嘗試:

SELECT `id`,
    if(`country` = 'India',count(id),0) as object1,
    if(`country` = 'America', count(id),0) as object2,
    if(`country` = 'USA',count(id),0) as object3
FROM `table`

上面給了我這樣的輸出:

id  | name  | object1   |   object2 | object3
---------------------------------------------
1   | India | 6         |   0       | 0     

我想要像這樣的輸出:

id  | name      | object1   |   object2 | object3
---------------------------------------------
1   | India     | 1         |   1       | 1     
1   | America   | 1         |   1       | 1
1   | USA       | 1         |   1       | 1

請有人幫我得到這個輸出。

我認為您需要條件聚合,但尚不清楚對象是什么。 根據數據,我可能會認為:

SELECT country as name,
       sum(name = 'abc') as abc,
       sum(name = 'xyz') as xyz
FROM `table`
group by country;

嘗試這個:

 SELECT `id`,`country`, count(`country`) as 'CountOfCountry'
    FROM `table`
    GROUP by id,Country

這樣,您就可以對每個獨特的國家/地區進行計數。 假設您所說的“對象”實際上是每個國家/地區的計數。

我不確定第三列應該是什么,因為您沒有支持它的樣本數據。 但是下面的內容( SQL Fiddle )如何:

SELECT country,
  SUM(CASE WHEN name = 'abc' THEN 1 ELSE 0 END) AS object1,
  SUM(CASE WHEN name = 'xyz' THEN 1 ELSE 0 END) AS object2,
  SUM(CASE WHEN name = 'nunya' THEN 1 ELSE 0 END) AS object3
FROM MyTable
GROUP BY country

我不確定您是否要在查詢中返回ID,因為示例輸出中的所有ID均為1,因此我不確定該如何代表您提供的示例數據,但我認為這是一個錯字。 這就是我想出的。 這是sql小提琴http://sqlfiddle.com/#!6/b763d/7

select id,country,
(select count(id) from things where country='india') as object1,
(select count(id) from things where country='america') as object2,
(select count(id) from things where country='usa') as object3
from things

現在,如果您不想使用ID,而只希望按國家/地區對事物進行分組,請執行以下操作。

select country,
(select count(id) from things where country='india') as object1,
(select count(id) from things where country='america') as object2,
(select count(id) from things where country='usa') as object3
from things
group by country

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM