我正在尝试测试多个列表中的项目是否属于所有列表的并集。联合在一起的所有项目都有一列,每个列表都有其他列。我想拥有true
或false
,具体取决于每个列表是否包含指定的项目。例如,有两个表,包含以下项目:
-- Table 1
Item
apple
orange
-- Table 2
Item
pear
grape
-- Resulting Table:
Item Table1 Table2
apple true false
orange true false
pear false true
grape false true
生成此查询的我的SQL如下:
WITH utable AS (SELECT item FROM table1 UNION
SELECT item FROM table2)
SELECT utable.item,
CASE WHEN EXISTS (SELECT table1.item, utable.item
FROM utable LEFT JOIN table1 ON utable.item = table1.item)
THEN 'true' ELSE 'false' END AS Table1,
CASE WHEN EXISTS (SELECT table2.item, utable.item
FROM utable LEFT JOIN table2 ON utable.item = table2.item)
THEN 'true' ELSE 'false' END AS Table2,
FROM utable;
我确信我的case语句不起作用,因为我不完全理解语法背后的逻辑。它总是写true
。我做错了什么,你有什么改进建议吗?谢谢你的任何建议。
答案 0 :(得分:1)
这样的事情:
WITH utable AS (SELECT item, 'true' AS table1, 'false' AS table2 FROM table1 UNION
SELECT item, 'false' AS table1, 'true' AS table2 FROM table2)
SELECT item, MAX(table1) AS table1, MAX(table2) AS table2
FROM utable
GROUP BY item
;
答案 1 :(得分:0)
使用子查询的情况,如果你总是想要一个真或假的结果?
create table x1 (item varchar(30))
insert into x1 (item) values ('apple')
insert into x1 (item) values ('orange')
create table x2 (item varchar(30))
insert into x2 (item) values ('pear')
insert into x2 (item) values ('grape')
with utable as ( select item from x1 union
select item from x2)
select utable.item
, case when item in (select item from x1) then 'True' else 'False' end as Table1
,case when item in (select item from x2) then 'True' else 'False' end as Table2
from utable