1

是否可以从同一个子查询中进行多项选择?这是我想构建的示例查询,但无法弄清楚如何去做(我意识到查询不起作用,我只是写它来传达我正在尝试做的事情):

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

谢谢!

4

4 回答 4

2

很难测试,因为您只提供了结果数据而不是输入数据,而且您没有在查询中使用别名,因此无法确定您的架构,但您可以使用如下内容:

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
于 2013-09-03T15:30:24.530 回答
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

内部查询返回您需要的所有列,外部查询将对其进行过滤。

于 2013-09-03T15:45:52.247 回答
0

您可能需要对相关子查询中别名的位置进行一些更改,但我认为除此之外您所做的应该可以工作。

我已经修改了您的查询:

选择 * 从
    (
    (select SUM(my_column) FROM stats WHERE condition = 404 AND my_id IN (t)) 作为总数,
    (select SUM(my_column) FROM stats WHERE condition = 404 AND condition2 404 AND my_id IN (t)) 作为total2,
    (选择 my_id
    从
    (
        选择编号
        来自统计
        加入 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 不为空
        AND条件2 404 GROUP BY my_id
    ) AS t) 作为 my_id
    ) X
于 2013-09-03T15:27:56.737 回答
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
于 2013-09-03T15:29:35.997 回答