是否可以从同一子查询中进行多项选择?这是一个我想要构建的示例查询,但是无法弄清楚如何执行它(我意识到查询不起作用,我只是写它来传达我正在尝试做的事情):< / p>
SELECT
(SUM(my_column) FROM stats WHERE condition = 404 AND my_id IN (t) as total),
(SUM(my_column) FROM stats WHERE condition = 404 AND condition2 <> 404 AND my_id IN (t) as total2),
SELECT my_id
FROM
(
SELECT id AS my_id
FROM stats
JOIN my_object ON stats.my_id = my_object.id
WHERE stats.condition = 404
AND my_object.created_at >= '2013-08-03 04:00:00.000000' AND my_object.created_at IS NOT NULL
AND condition2 <> 404 GROUP BY my_id
) AS t
我在postgres工作,但更喜欢ANSI SQL解决方案。
结果数据:
id total total2
1 5 NULL
2 NULL 6
3 6 9
4 1 1235
谢谢!
答案 0 :(得分:2)
很难测试,因为你只提供结果数据而不是输入数据,而且你没有在查询中使用别名,所以不可能确定你的模式,但你可以使用这样的东西: / p>
select
s.my_id,
sum(s.my_column) as total,
sum(case when s.condition2 <> 404 then s.my_column else 0 end) as total2
from stats as s
inner join my_object as o on o.id = s.my_id
where
s.condition = 404 and
o.created_at >= '2013-08-03 04:00:00' and
o.created_at is not null
group by s.my_id
答案 1 :(得分:0)
您可能需要对相关子查询中别名的位置进行一些更改,但我认为除此之外,您所做的工作应该有效。
我已经重新设计了你的问题:
SELECT * from ( (select SUM(my_column) FROM stats WHERE condition = 404 AND my_id IN (t)) as total, (select SUM(my_column) FROM stats WHERE condition = 404 AND condition2 404 AND my_id IN (t)) as total2, (SELECT my_id FROM ( SELECT id FROM stats JOIN my_object ON stats.my_id = my_object.id WHERE stats.condition = 404 AND my_object.created_at >= '2013-08-03 04:00:00.000000' AND my_object.created_at IS NOT NULL AND condition2 404 GROUP BY my_id ) AS t) as my_id ) x
答案 2 :(得分:0)
你需要子查询吗?
SELECT
ID,
SUM(my_column),
SUM(CASE WHEN condition2 <> 404 THEN my_column ELSE 0 END)
FROM stats
JOIN my_object
ON stats.my_id = my_object.id
WHERE stats.condition = 404
AND my_object.created_at >= '2013-08-03 04:00:00.000000'
AND my_object.created_at IS NOT NULL
GROUP BY ID
答案 3 :(得分:0)
这就是我写外部查询的方式:
SELECT
my_id AS id,
SUM(CASE WHEN condition = 404 AND my_id IN (t) THEN my_column ELSE 0 END) AS total,
THEN my_column ELSE 0 END) AS total,
SUM(CASE WHEN condition = 404 AND condition2 <> 404 AND my_id IN (t)
THEN my_column ELSE 0 END) AS total2
FROM (
SELECT my_id, condition, condition2, etc.
...
) AS subqry
GROUP BY my_id
内部查询返回您需要的所有列,外部将过滤它。