2015-09-15 76 views
0

我有表,我有兩列briefengbriefbng,我需要的總空的以適當的方式計數,而不是空值:與指定的列MySQL的總和

這裏是我的SQL代碼:

SELECT 
Sum(If(brief_english Is Null, 1, 0)) AS briefeng, 
Sum(If(brief_english Is NOT Null, 1, 0)) AS briefengnotnull, 

Sum(If(brief_bangla Is Null, 1, 0)) AS briefbng 
FROM synopsis; 

但它返回象這樣的結果:

+----------+-----------------+----------+ 
| briefeng | briefengnotnull | briefbng | 
+----------+-----------------+----------+ 
|  946 |    896 |  841 | 
+----------+-----------------+----------+ 

但我需要的結果在這方面

+----------+--------------+ 
| status | total   | 
+----------+--------------+ 
| briefeng |   946 | 
+----------+--------------+ 
| briefengnotnull | 896 | 
+----------+--------------+ 
| briefengnotnull | 841 | 
+----------+--------------+ 

我該怎麼做?我找不到一個簡單而有效的方法。

+1

使用'union'或'union all' – RubahMalam

回答

0

使用工會或工會所有這樣的:

SELECT 
'briefeng' as status, 
Sum(If(brief_english Is Null, 1, 0)) AS total 
FROM synopsis 
UNION ALL 
SELECT 
'briefengnotnull' as status, 
Sum(If(brief_english Is NOT Null, 1, 0)) AS total 
FROM synopsis 
UNION ALL 
SELECT 
'briefbng' as status, 
Sum(If(brief_bangla Is Null, 1, 0)) AS total 
FROM synopsis 

Difference between Union All and Union

+0

不能使用union作爲symfony2不支持 –

+0

@ahmad你可以看看這個(如何在symfony中使用union):http://stackoverflow.com/questions/ 7981549/sql-query-with-union-in-doctrine-symfony – RubahMalam

+0

我知道,但問題是我不想與pdo創建依賴關係,而是想與orm保持聯繫 –

0
SELECT count(*) FROM tablename WHERE a IS NULL 
UNION ALL 
SELECT count(*) FROM tablename WHERE a IS NOT NULL 

select sum(case a when null then 1 else 0) "Null values", 
     sum(case a when null then 0 else 1) "Non-null values" 
from tablename; 

select sum(case when a is null then 1 else 0 end) count_nulls 
    , count(a) count_not_nulls 
    from tablename; 
+0

沒有一個可行,我之前嘗試過相同的事情,使用union作爲symfony2和doctrine querybuilder不支持union –

0

這是一個不擇手段之類的做法,但如果你創建一個包含標題與此架構

CREATE TABLE `titles` (
    `title` varchar(255) CHARACTER SET latin1 NOT NULL, 
    PRIMARY KEY (`title`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin 

輔助表和該數據

insert into `titles`(`title`) values ('briefeng'), ('briefengnotnull'), ('briefbng'); 

使用此查詢

SELECT t.title, IF(a.total IS NOT NULL, a.total, IF(b.total IS NOT NULL, b.total, c.total)) AS total FROM 
titles t 
LEFT JOIN (SELECT 'briefeng' AS title, SUM(IF(brief_english IS NULL, 1, 0)) AS total FROM synopsis) a ON a.title=t.title 
LEFT JOIN (SELECT 'briefengnotnull' AS title, SUM(IF(brief_english IS NULL, 0, 1)) AS total FROM synopsis) b ON b.title=t.title 
LEFT JOIN (SELECT 'briefbng' AS title, SUM(IF(brief_bangla IS NULL, 1, 0)) AS total FROM synopsis) c ON c.title=t.title 

得到這個結果(取決於大綱表中的記錄)

+-----------------+-------+ 
| title   | total | 
+-----------------+-------+ 
| briefbng  |  3 | 
| briefeng  |  1 | 
| briefengnotnull |  4 | 
+-----------------+-------+