是否有可能以某种方式在TD中的case语句中使用select子句(而不是进行连接)?
我想做这样的事情:
SELECT
id,
, count(*)
, (CASE WHEN id IN ANY (SELECT DISTINCT ID FROM PARTICIPANTS_TABLE)
THEN 1 ELSE 0
end) AS participant
FROM EVERYONE_TABLE
GROUP BY id
我得到的错误是“CASE表达式的WHEN子句中的非法表达。”
答案 0 :(得分:4)
您应该将SELECT更改为标量子查询
SELECT
id
, COUNT(*)
, (CASE WHEN id = (SELECT MIN(ID) FROM PARTICIPANTS_TABLE AS p
WHERE p.id = e.id)
THEN 1 ELSE 0
END) AS participant
FROM EVERYONE_TABLE AS e
GROUP BY id
但我总是遵循的基本规则是避免选择列表中的标量子查询,根据我的经验,他们往往会有一个糟糕的优化。
我会将其重写为外部联接(imho这是人们编写标量子查询的主要原因,在大多数情况下,它们只是隐藏外部联接):
SELECT
t1.id
, COUNT(*)
, COUNT(t2.ID) AS participant
FROM EVERYONE_TABLE AS t1
LEFT JOIN
(SELECT DISTINCT ID FROM PARTICIPANTS_TABLE) AS t2
ON t1.id = t2.id
GROUP BY t1.id
另外,这种语法更容易理解,至少对我而言: - )
答案 1 :(得分:0)
是的,这应该使用正确的语法:
SELECT id,
(CASE WHEN id IN (SELECT DISTINCT ID FROM PARTICIPANTS_TABLE)
THEN 1 ELSE 0
end) AS participant;
不需要distinct
:
SELECT id,
(CASE WHEN id IN (SELECT ID FROM PARTICIPANTS_TABLE)
THEN 1 ELSE 0
end) AS participant;