2011-09-01 85 views
5

通常我覺得用SQL查詢非常有信心,但是這其中有我抓我的頭。我覺得這應該是一個快速解決方案,但我只是沒有看到它。MySQL:如何分別從列計數?

我試圖做在同一個表上的多個值的數量,在一個查詢。

不介意「0000000000000000」這只是代表一個空字節數組。

有沒有一種簡單的方法,以這些查詢結合?

SELECT COUNT(ssn) 
FROM patients 
WHERE ssn="0000000000000000"; 

SELECT COUNT(firstname) 
FROM patients 
WHERE firstname="0000000000000000" 

SELECT COUNT(lastname) 
FROM patients 
WHERE lastname="0000000000000000" 

etc... 

回答

2

你可以做這樣的事情 -

SELECT COUNT(ssn) AS patient_count, 'ssn' AS count_type 
FROM patients 
WHERE ssn="0000000000000000"; 
UNION 
SELECT COUNT(firstname) AS patient_count, 'firstname' AS count_type 
FROM patients 
WHERE firstname="0000000000000000" 
UNION 
SELECT COUNT(lastname) AS patient_count, 'lastname' AS count_type 
FROM patients 
WHERE lastname="0000000000000000" 
+0

有沒有一種方法可以轉動桌子?我的意思是將我的瓷磚作爲標題而不是值更好。 – theangryhornet

+2

你可以把UNION ALL而不是UNION,只是爲了保存SQL服務器的一些冗餘工作。 – James

1

與UNION嘗試

SELECT COUNT(ssn) 
FROM patients 
WHERE ssn="0000000000000000"; 
UNION 
SELECT COUNT(firstname) 
FROM patients 
WHERE firstname="0000000000000000" 
UNION  
SELECT COUNT(lastname) 
FROM patients 
WHERE lastname="0000000000000000" 
+2

你會想在這裏使用'UNION ALL'。如果兩個(甚至全部三個)計數恰好相同,那麼'UNION'會將它們作爲重複項消除。 –

+0

不知道我是否喜歡這個,因爲你無法區分哪些是哪個。 – theangryhornet

+0

你可以把另一列與描述來解決這個 –

6
SELECT SUM(CASE WHEN ssn = '0000000000000000' THEN 1 ELSE 0 END) AS ssn_count, 
     SUM(CASE WHEN firstname = '0000000000000000' THEN 1 ELSE 0 END) AS first_count, 
     SUM(CASE WHEN lastname = '0000000000000000' THEN 1 ELSE 0 END) AS last_count 
    FROM patients 
    WHERE ssn = '0000000000000000' 
     OR firstname = '0000000000000000' 
     OR lastname = '0000000000000000' 
+0

這很該死的涼爽。您如何看待它在性能上與下面的「聯盟」解決方案相比? – Marvo

+3

@Marvo:我的標準答案是嘗試兩種比較。我認爲這會更好,因爲它是1選擇與3。 –

+0

非常有趣的方法! – theangryhornet

1

我想這將工作?

SELECT * 
FROM 
(SELECT COUNT(ssn) AS ssn_count 
FROM patients 
WHERE ssn="0000000000000000") AS ssn 
CROSS JOIN 
(SELECT COUNT(firstname) AS firstname_count 
FROM patients 
WHERE firstname="0000000000000000") AS firstname 
CROSS JOIN 
(SELECT COUNT(lastname) AS lastname_count 
FROM patients 
WHERE lastname="0000000000000000") AS lastname