2015-12-21 50 views
0

我有一個表:如何在select中過濾空值?

DataTable: 
id int, 
user_id int, 
field_id int, 
value varchar 

DataExample:

id user_id field_id value 
1  1   1  'Peter' 
2  1   2  56 
3  1   3  100 
4  2   1  'Buzz' 
5  2   2  47 
6  2   3  120 
7  3   1  'Wolf' 
8  3   2  null 
9  3   3  null 

我想field_id財產來分隔值列:

Name Age  Score 
Peter 56  100 
Buzz 47  120 

我做的:

SELECT id, MAX(Name) AS Name, MAX(Age) AS Age, MAX(Score) AS Score 
FROM (
SELECT u.id 
CASE 
    WHEN field_id = 1 THEN value 
END as Name, 
CASE 
    WHEN field_id = 2 THEN value 
END as Age, 
CASE 
    WHEN field_id = 3 THEN value 
END as Score 
FROM Users u 
INNER JOIN DataTable t ON (t.user_id=u.id) 
) AS sub 
GROUP BY id; 

這是很好的作品。但現在我想過濾空值。我的意思是我不想選擇AgeScore = null。我嘗試在CASE塊中添加is not null,但它沒有幫助。
任何建議?

+0

嘗試'ifnull()'。一探究竟。 – MaxPD

+0

爲什麼在CASE塊?你忘了'WHERE'嗎? – i486

+0

請問您可以使用NULL將行添加到數據示例並顯示它將如何影響輸出? – Uriil

回答

2

做一個雙自聯接:

select t1.value as name, t2.value as Age, t3.value as Score 
from (select userid, value from DataTable where field_id = 1) as t1 
join (select userid, value from DataTable where field_id = 2) as t2 ON t1.userid = t2.userid 
join (select userid, value from DataTable where field_id = 3) as t3 ON t1.userid = t3.userid 

第一個子查詢返回的名字,第二個返回年齡和第三得分。

+0

它的作品!謝啦。 –

+0

不客氣! – jarlh

0
SELECT id, MAX(Name) AS Name, MAX(Age) AS Age, MAX(Score) AS Score 
FROM (
SELECT u.id 
CASE 
    WHEN field_id = 1 THEN value 
END as Name, 
CASE 
    WHEN field_id = 2 THEN value 
END as Age, 
CASE 
    WHEN field_id = 3 THEN value 
END as Score 
FROM Users u 
INNER JOIN DataTable t ON (t.user_id=u.id) 
    WHERE value IS NOT NULL -------------------here 
) AS sub 
GROUP BY id; 
+0

我仍然得到一個空值, –

+1

然後檢查該字段是否爲空而不是NULL – MaxPD