我有以下查詢來獲取兩個不同的罪名:怎麼做,而不是工會SUM
select count(*)
from title_title where tv_show_id is null
union
select count(distinct tv_show_id)
from title_title where tv_show_id is not null
有沒有一種簡單的方法來添加兩個一起SQL內而不是做它的外面加?
我有以下查詢來獲取兩個不同的罪名:怎麼做,而不是工會SUM
select count(*)
from title_title where tv_show_id is null
union
select count(distinct tv_show_id)
from title_title where tv_show_id is not null
有沒有一種簡單的方法來添加兩個一起SQL內而不是做它的外面加?
由於兩個查詢都使用同一個表,因此可以將聚合函數中的where
子句轉換爲case
表達式,然後添加結果。需要注意的是count
,最喜歡的聚集函數忽略null
S,所以這可以相對整齊地做到:
SELECT COUNT(CASE WHEN tv_show_id IS NULL THEN 1 END) +
COUNT(DISTINCT tv_show_id) -- nulls are ignored anyway
FROM title_title
請原諒MSSQL
的答案,但我相信你應該能夠做到這一點(或非常類似的東西)的MySQL
:
SELECT (COUNT(tt.*) + COUNT(tt2.tv_show_id)) AS Total
FROM title_title tt
JOIN title_title tt2 ON tt.tv_show_id = tt2.tv_show_id
WHERE tt.tv_show_id IS NULL
AND tt2.tv_show_id IS NOT NULL
執行JOIN
回到談判桌前,抓住每個(tt.*
和tt2.tv_show_id
)計數和計數相加的方式。
簡單好用,比我的答案:) – levelonehuman
用'CASE'聲明好主意好。 – David542