I have the following table:
CREATE TABLE yow(
userid INT,
itemid INT,
feedback INT,
value INT)
(userid,itemid,feedback) can be considered a primary key, where each of these tuples contains a value.
I want a query which returns a table with the following columns:
userid | itemid | col0 | col1 | col2
Where col0 contains value
for all rows in yow
where feedback = 0, and col1 contains value
where feedback = 1 and so on.
I have a somewhat working query:
SELECT
yow.userid AS uid,
yow.itemid AS iid,
isNull(col0.value, 0) AS col0,
IsNull(col1.value, 0) AS col1,
IsNull(col2.value, 0) AS col2
FROM yow
LEFT JOIN yow AS col0 ON col0.userid=yow.userid AND col0.itemid=yow.itemid
LEFT JOIN yow AS col1 ON col1.userid=yow.userid AND col1.itemid=yow.itemid
LEFT JOIN yow AS col2 ON col2.userid=yow.userid AND col2.itemid=yow.itemid
WHERE col0.feedback = 0
AND col1.feedback = 1
AND col2.feedback = 2
GROUP BY uid, iid
The problem is that I can have a value for (userid,itemid) in col1 or col2 but not the others. With this query, those rows are filtered out instead of the missing cells defaulting to 0.
As an example, I am getting something like this:
+-------+-------+--------+--------+--------+
| UID | IID | COL0 | COL1 | COL2 |
+-------+-------+--------+--------+--------+
| 1 | 101 | 23 | 22 | 241 |
| 1 | 101 | 51 | 13 | 159 |
| 2 | 102 | 22 | 55 | 152 |
| 3 | 103 | 14 | 41 | 231 |
+-------+-------+--------+--------+--------+
But instead I want something like this, where the missing values of col0 are defaulted to 0.
+-------+-------+--------+--------+--------+
| UID | IID | COL0 | COL1 | COL2 |
+-------+-------+--------+--------+--------+
| 1 | 101 | 23 | 22 | 241 |
| 1 | 101 | 51 | 13 | 159 |
| 1 | 102 | 0 | 15 | 142 |
| 2 | 102 | 22 | 55 | 152 |
| 2 | 103 | 0 | 45 | 92 |
| 3 | 103 | 14 | 41 | 231 |
+-------+-------+--------+--------+--------+
Can anyone suggest a fix to my query or perhaps propose a better one? I'm running this on H2, so I reckon the query should be somewhat standard. Thanks:)