[英]SQL Query. How can I combine these two tables?
我有兩個表:
Table A
|user_id| |type |revenues|
101, comic, 10
101, adventure,30
101, comic, 10
102, romantic, 20
和
Table B
|type |
comic
adventure
romantic
animate
其中表 B 包含整個書籍類型。 表 A 包含事務。 如何將兩張表組合成一張新表,以便顯示每個人的交易。 (注意:1,對於一個人沒有購買的book_types,收入應該為零。2,對於相同的user_id和type組合的sum(revenues))。 例如,一個新表應該是這樣的:
Table New
101, comic, 20
101, adventure, 30
101, romantic, 0
101, animate, 0
102, comic, 0
102, adventure, 0
102, romantic, 20
102, animate, 0
要創建表,可以使用以下代碼:
create table A(usr_id integer, book_type varchar(100), revenues integer);
create table B(book_type varchar(100));
insert into A(usr_id, book_type, revenues) values(101, "comic", 10);
insert into A(usr_id, book_type, revenues) values(101, "comic", 10);
insert into A(usr_id, book_type, revenues) values(101, "adventure",30);
insert into A(usr_id, book_type, revenues) values(102, "romantic",20);
insert into B(book_type) values("comic");
insert into B(book_type) values("adventure");
insert into B(book_type) values("romantic");
insert into B(book_type) values("animate");
如果只有一種user_id,我可以想出一個解決方案(見下文)。 但是不知道user_id多的情況怎么處理。
select case when tmp.user_id is NUll then 101 else tmp.usr_id END,
B.book_type, case when tmp.revenues is NULL then 0 else tmp.revenues
END
from
(
select usr_id, book_type, sum(revenues) as revenues
from A
group by usr_id, book_type
) tmp
right join B on tmp.book_type = B.book_type
您可以使用如下所示的 CROSS 和 LEFT 連接組合來獲得所需的輸出。
SELECT A.user_id,B.type,
CASE WHEN ISNULL(C.revenues) = 1 THEN 0 ELSE C.revenues END
FROM (
SELECT DISTINCT user_id
FROM Table_A) A
CROSS JOIN Table_B B
LEFT JOIN Table_A C ON A.user_id = C.user_id AND B.type = C.type
ORDER BY A.user_id,B.type
與之前的答案類似,但包括給定user_id
和type
組合的收入總和:
SELECT q1.user_id, q1.type, IFNULL(SUM(revenues),0)
FROM
(
SELECT DISTINCT user_id, TableB.type
FROM TableA CROSS JOIN TableB
) q1
LEFT JOIN TableA ON q1.user_id = TableA.user_id AND q1.type = TableA.type
GROUP BY q1.user_id, q1.type
ORDER BY q1.user_id;
方法是:
交叉連接兩個表以生成所有可能的 user_id 和類型配對
連接新的交叉連接臨時表和表 A 的收入
將 user_id 和類型組合的收入相加,或者在 null 的情況下給出 0
SQLFiddle在這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.