2015-04-03 58 views
0

現在我想對列中包含值或不爲空的行進行計數。我是SQL的初學者;我的SQL查詢如下:Sql計數包含一些值的行

select count(news) AS news_count, count(`msg`) as msg_count , count('req') as req_count 
from news_msg_activity 
where news!='' 
UNION 
select count(news) AS news_count, count(`msg`) as msg_count , count('req') as req_count 
from news_msg_activity 
where msg!='' 
UNION 
select count(news) AS news_count, count(`msg`) as msg_count , count('req') as req_count 
from news_msg_activity 
where req!='' 

當我運行查詢時,它給出了兩個數字的結果。但是我需要一個單一的數字結果來計算上述操作記錄的數量。我不知道如何編寫該查詢。有誰能夠幫助我?

,但我需要一個像

news_count || msg_count || req_count       
    2  ||  2  || 3 

回答

2

裹在子查詢中查詢。

SELECT * -- here you can sum, count or whatever elese you need 
FROM (
    -- your query goes here 
) as src 

或者乾脆

select 
    sum(news!='') AS news_count 
    , sum(msg!='') as msg_count 
    , sum(req!='') as req_count 
from news_msg_activity 

布爾語句評估爲整數0/1(假/真) - 此作爲在條件滿足的計數。

檢查小提琴:http://sqlfiddle.com/#!9/8c780/1

+0

需要更清楚 – 2015-04-03 13:18:59

+0

謝謝..現在正在工作 – 2015-04-03 13:30:31

2

COUNT(column)將已返回的非空記錄的數目,所以,除非我誤解你想做什麼,你可以讓這個更簡單。下面的查詢應返回的非空記錄數爲每個字段:

select count(news) AS news_count 
, count(`msg`) as msg_count 
, count(req) as req_count 
from news_msg_activity 

如果您關注的是從計數排除空字符串,您可以使用NULLIF功能:

select count(nullif(news, '')) AS news_count 
, count(nullif(`msg`, '')) as msg_count 
, count(nullif(req, '')) as req_count 
from news_msg_activity 
+0

最後一列的數量('請求')因爲req_count不工作..它統計所有行 – 2015-04-03 13:25:05

+0

哦,對,對不起。我只是複製了你的語法而沒有考慮它,但是你不能用單引號來轉義字段名。這只是被解釋爲一個常數。試試我的編輯版本。 – 2015-04-03 13:27:22

0

你確定你確實需要UNION?也許這樣的事情?

SELECT 
    * 
FROM 
    (SELECT 
     count(news) AS news_count 
    FROM 
     news_msg_activity 
    WHERE 
     news!= '') a, 
    (SELECT 
     count(msg) as msg_count 
    FROM 
     news_msg_activity 
    WHERE 
     msg!= '') b, 
    (SELECT 
     count(req) as req_count 
    FROM 
     news_msg_activity 
    WHERE 
     req!= '') c 

此外,使字段news, msg, req - 表的方案中的NOT NULL。因爲現在count()用字段的null值對行進行計數。您可以將IS NOT NULL添加到查詢中,但更好的解決方案是使用默認值設置表格方案中的NOT NULL。這將使您免受未來「bug」的困擾。