繁体   English   中英

SQL 查询。 我怎样才能把这两个表结合起来?

[英]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_idtype组合的收入总和:

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;

方法是:

  1. 交叉连接两个表以生成所有可能的 user_id 和类型配对

  2. 连接新的交叉连接临时表和表 A 的收入

  3. 将 user_id 和类型组合的收入相加,或者在 null 的情况下给出 0

SQLFiddle在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM