2017-04-20 94 views
-1

我高清以下的數據庫表,我想通過顏色進行計數和分組。我是SQL的一名學生和初學者。任何人都可以教代碼嗎?SQL組By和Count功能

SQL-CountColor:

SQL-CountColor

我曾嘗試:

Select COLOR, 
    sum(case when Blue = 1 then 1 else 0 end) as Blue_count, 
    sum(case when Red then 1 else 0 end) as Red_count, 
    sum(case when Yellow then 1 else 0 end) as Yellow_count, 
    sum(case when Black then 1 else 0 end) as Black_count, 
    sum(case when Green then 1 else 0 end) as Green_count, 
from TAB_GROUP 
group by COLOR; 
+1

你嘗試過什麼嗎? – Milney

+1

這不是StackOverflow的工作原理,讓我說,這不是你將如何學習SQL(或其他任何東西)。像這樣的問題已經在多個網站上被多次詢問(包括SO),所有你需要做的只是一點研究。如果在這樣做之後,你仍然無法解決這個問題,請回到這裏併發佈一個問題,描述你嘗試過的和錯誤的,並且你會找到幫助。關鍵詞tip:搜索「group by」,「count」,「case」,「pivot」,您可能會發現有趣的資源。 –

+0

對不起,我忘記發佈我試過的東西 – DerrickWong

回答

0

與您查詢的問題是,你混合兩種方法,既有效但不兼容。

第一個使用case聲明,就像@LONG在其答案中所做的那樣,並且沒有問題,但不需要group by;你已經通過在每一欄中給予不同的條件「人爲地」分組了;

select sum(case when Blue = 1 then 1 else 0 end) as Blue_count, 
     sum(case when Red then 1 else 0 end) as Red_count, 
     sum(case when Yellow then 1 else 0 end) as Yellow_count, 
     sum(case when Black then 1 else 0 end) as Black_count, 
     sum(case when Green then 1 else 0 end) as Green_count 
from TAB_GROUP 

另一種方法是使用group by,並且它也很有效,但你只需要計算行數爲每個組

select COLOR, count(*) as CNT 
from TAB_GROUP 
group by COLOR 

這會給你一個結果是一樣的如所期望的一個,但與倒

COLOR | CNT 
Blue | 2 
Red | 2 
Yellow | 1 
Black | 1 
Green | 1 

要移動行列,你需要旋轉功能,可能取決於你全光照的數據庫,其語法的行和列G。這使得這種方法更復雜,但是在可能值的數量增加的情況下也更通用。

0
select  sum(case when color = 'blue' then 1 else 0 end) as 'Blue', 
      sum(case when color = 'red' then 1 else 0 end) as 'Red', 
      sum(case when color = 'yellow' then 1 else 0 end) as 'Yellow', 
      sum(case when color = 'Black' then 1 else 0 end) as 'Black', 
      sum(case when color = 'Green' then 1 else 0 end) as 'Green' 
From Table 
+1

看起來像你真的很急於回答... – Rahul

+0

@Rahul,不是真的,實際上在我的手機上回答。 – LONG

1

你應該尋找一點點,這是一個很常見的SQL語句。

select COLOR, count(*) from TAB_GROUP group by COLOR 
0

你的查詢基本上是正確的。所有你需要做的是去除GROUP BY並修復case指列數據:

select sum(case when color = 'Blue' then 1 else 0 end) as Blue_count, 
     sum(case when color = 'Red' then 1 else 0 end) as Red_count, 
     sum(case when color = 'Yellow' then 1 else 0 end) as Yellow_count, 
     sum(case when color = 'Black' then 1 else 0 end) as Black_count, 
     sum(case when color = 'Green' then 1 else 0 end) as Green_count 
from TAB_GROUP;