2012-09-07 49 views
0

我有一個奇怪的問題與MySQL計數。當我執行再次mysql「計數不同」

SELECT a.inc AS inc, 
     a.cls AS cls, 
     a.ord AS ord, 
     a.fam AS fam, 
     a.subfam AS subfam, 
     a.gen AS gen, 
     aspec AS spec, 
     asubspec AS subspec 
    FROM a 
    WHERE (ainc = 11) 

我獲得:

,這是很正常的,因爲我有2個記錄。

當我執行

SELECT COUNT(DISTINCT a.inc) AS inc, 
     COUNT(DISTINCT a.cls) AS cls, 
     COUNT(DISTINCT a.ord) AS ord, 
     COUNT(DISTINCT a.fam) AS fam, 
     COUNT(DISTINCT asubfam) AS subfam, 
     COUNT(DISTINCT a.gen) AS gen, 
     COUNT(DISTINCT a.spec) AS spec, 
     COUNT(DISTINCT a.subspec) AS subspec 
    FROM a 
    WHERE (a.inc = 11) 
    GROUP BY a.inc 

我獲得

,並因爲當你看到gen, spec and subspec有一行0值,這是奇怪的。 我知道count distinct不會計入零值。我要統計所有值= 0和計數明顯我想

`1 | 2 | 2 | 2 | 2 | 1 | 1 | 1 |` 

之後我也嘗試:

SELECT COUNT(DISTINCT a.inc) AS inc, 
     SUM(if(a.cls <> 0, 1, 0)) AS cls, 
     SUM(if(a.ord <> 0, 1, 0)) AS ord, 
     SUM(if(a.fam <> 0, 1, 0)) AS fam, 
     SUM(if(a.subfam <> 0, 1, 0)) AS subfam, 
     SUM(if(a.gen <> 0, 1, 0)) AS gen, 
     SUM(if(a.spec <> 0, 1, 0)) AS spec, 
     SUM(if(a.subspec <> 0, 1, 0)) AS subspec 
    FROM a 
GROUP BY a.inc 

SELECT COUNT(DISTINCT a.inc) AS inc, 
      SUM(DISTINCT if(a.cls <> 0, 1, 0)) AS cls, 
      SUM(DISTINCT if(a.ord <> 0, 1, 0)) AS ord, 
      SUM(DISTINCT if(a.fam <> 0, 1, 0)) AS fam, 
      SUM(DISTINCT if(a.subfam <> 0, 1, 0)) AS subfam, 
      SUM(DISTINCT if(a.gen <> 0, 1, 0)) AS gen, 
      SUM(DISTINCT if(a.spec <> 0, 1, 0)) AS spec, 
      SUM(DISTINCT if(a.subspec <> 0, 1, 0)) AS subspec 
FROM a 
GROUP BY a.inc 

,但它不是在第一,因爲工作方法不會使所有重複值大於0;在第二種情況下,它只給1和0。
那麼,有人可以幫助我嗎?先謝謝你。獅子座

+1

什麼讓你覺得DISTINCT不計算0值?它不會計算_NULL_值,但NULL不等於0. – Barmar

回答

3

我知道count distinct不會計入零值。

我不知道你在哪裏得到了這個想法,但它不正確。也許你正在考慮NULL值?獲得所需結果的一種方法是將0視爲不同數量的NULL。

嘗試是這樣的(我也刪除由組,這是沒有幫助):

SELECT COUNT(DISTINCT case when a.inc = 0 then null else a.inc end) AS inc, 
     COUNT(DISTINCT case when a.cls = 0 then null else a.cls end) AS cls, 
     COUNT(DISTINCT case when a.ord = 0 then null else a.ord end) AS ord, 
     COUNT(DISTINCT case when a.fam = 0 then null else a.fam end) AS fam, 
     COUNT(DISTINCT case when a.subfam = 0 then null else a.subfam end) AS subfam, 
     COUNT(DISTINCT case when a.gen = 0 then null else a.gen end) AS gen, 
     COUNT(DISTINCT case when a.spec = 0 then null else a.spec end) AS spec, 
     COUNT(DISTINCT case when a.subspec = 0 then null else a.subspec end) AS subspec 
    FROM a 
    WHERE (a.inc = 11) 
+0

非常感謝! –

2
SELECT COUNT(DISTINCT a.inc) AS inc, 
     COUNT(DISTINCT NULLIF(a.cls, 0)) AS cls, 
     COUNT(DISTINCT NULLIF(a.ord, 0)) AS ord, 
     COUNT(DISTINCT NULLIF(a.fam, 0)) AS fam, 
     COUNT(DISTINCT NULLIF(a.subfam, 0)) AS subfam, 
     COUNT(DISTINCT NULLIF(a.gen, 0)) AS gen, 
     COUNT(DISTINCT NULLIF(a.spec, 0)) AS spec, 
     COUNT(DISTINCT NULLIF(a.subspec, 0)) AS subspec 
FROM a 
+1

NULLIF是一個MySQL函數,與Ike Walter的答案中的CASE構造相當。 – Barmar

+0

我的上帝這很優雅!謝謝! :) –