我是一个完整的sql noob,所以我为后面的sql butchering道歉... 这是我正在尝试做的伪代码:
count(
join(
select( * from table X where a='stuff' and b='junk' ) as X1
select( * from table X where a='arg' and b='blarg' ) as X2
select( * from table X where a='narf' and b='foo' ) as X3
) where X1.c = X2.c = X3.c
)
是否可以在一个查询中获得此结果?
答案 0 :(得分:2)
select count(*) from
(select * from table X where a='stuff' and b='junk') x1
join
(select * from table X where a='arg' and b='blarg' ) x2
on x1.c=x2.c
join
( select * from table X where a='narf' and b='foo' ) X3
on x2.c=x3.c
答案 1 :(得分:1)
如果我猜测你真正想要的是什么,那就是“c”的计数,它包含a
和b
列中的所有三个条件。如果是这种情况,则以下工作:
select count(*)
from (select c
from table X
group by c
having sum(CASE WHEN a = 'stuff' AND b = 'junk' THEN 1 ELSE 0 END) > 0 and
sum(CASE WHEN a = 'arg' AND b = 'blarg' THEN 1 ELSE 0 END) > 0 and
sum(CASE WHEN a = 'narf' AND b = 'foo' THEN 1 ELSE 0 END) > 0
) t
答案 2 :(得分:0)
SELECT c,
SUM(CASE WHEN a = 'stuff' AND b = 'junk' THEN 1 ELSE 0 END) AS X1,
SUM(CASE WHEN a = 'arg' AND b = 'blarg' THEN 1 ELSE 0 END) AS X2,
SUM(CASE WHEN a = 'narf' AND b = 'foo' THEN 1 ELSE 0 END) AS X3
FROM table_X
GROUP BY c
答案 3 :(得分:0)
表x中的
你想要三组记录,每一组都是来自同一个表X的选择
到目前为止,我们有三个“逻辑视图”,它们是X的独立子集,分别称为X1,X2,X3
join(...)其中X1.c = X2.c = X3.c
解释可能有点含糊不清,令人困惑,让我们试试:
字面上: c是表X
的字段的名称所有这些情况看起来都特别奇怪,所以我提出了另一种解释,这是一种最常见的情况,但并非字面上坚持加入的概念:
我们想要计算X1,X2,X3的联合;
在这种情况下,解决方案是:
SELECT COUNT(*) FROM X
WHERE (a='stuff'AND b='junk')
OR (a='arg' AND b='blarg')
OR (a='narf' AND b='foo')
警告:我完全理解“联盟”与“联接”完全不同,因此如果您真的意味着加入,这种解释可能完全错误,但探索这种意义的可能性。