2012-06-15 36 views
0

我正在使用MySQL查詢編寫報告。它有多個我報告的列。其中,有一列包含許多不同的值(只有一個值前行)。該列中有兩個特定值需要計算。mysql:針對單個列計數發生特定值的行數

ID Name has passed Type 
1 abc  yes (1) z 
2 xyz  yes (1) x 
3 cde  no (0) y 
4 abc  yes (1) z 
5 cde  no (0) z 
6 xyz  no (0) y 

我預期的結果是:

For Type x 
total records = 1 
yes count = 1  
total abc = 0 
total cde = 0 

For Type y 
total records = 2 
yes count = 0  
total abc = 0 
total cde = 1 

For Type z 
total records = 3 
yes count = 2 
total abc = 2 
total cde = 1 

注意,我們不要指望名字XYZ或任何其他名稱的最終結果,然後按類型分組。

回答

0
SELECT 
    type, 
    COUNT(*) AS total_records, 
    COUNT(IF(has_passed, 1, NULL)) AS yes_count, 
    COUNT(IF(name = 'abc', 1, NULL)) AS total_abc, 
    COUNT(IF(name = 'cde', 1, NULL)) AS total_cde 
FROM 
    table 
GROUP BY 
    type 
+0

PERFECTO!非常感謝,贊恩。我雖然我在來到StackOverflow之前試過這個查詢。它完全如我所願。 –

0

關閉我的頭頂部(沒有獲得用於測試的數據庫,現在,對不起)...也許像這樣的工作(假設你存儲0和1通過了」 「)?

SELECT 
    type, 
    SUM(passed) as "Yes count", 
    SUM(case when name = 'abc' then 1 else 0 end) as "Total abc", 
    SUM(case when name = 'cde' then 1 else 0 end) as "Total cde", 
    COUNT(1) as "Total records" 
FROM 
    myTable 
GROUP BY 
    type 
; 
+0

呃...被我毆打了。我也認爲我的示例可能使用Oracle語法。雖然它的要點是相同的。 –

+0

雖然解決方案的優點是'CASE'表達式在其他DBMS中更加標準,而'IF'主要是MySQL特定的。 –

+0

是的,我儘可能保持標準。在這種情況下,MySQL的版本更短,但使用'CASE'的標準方式更易於理解IMO。無論如何,要麼做的工作:O) –