尝试使用子查询但子查询返回带有限定符的多行

时间:2016-10-15 13:15:19

标签: mysql subquery

我正在编写查询以根据7天滚动统计信息生成图表。 newpostclosedpost工作正常,但当我尝试设置subquery returns more than one row等限定符以显示WHERE closed IS NOT NULL AND (sent = 0 OR sent =1) AND created >= DATE(NOW()) - INTERVAL 7 DAY GROUP BY DATE(created))时,我获得了solvedpost。我不知道如何开展这项工作。任何帮助都是适当的

我的疑问:

SELECT 
    DATE(created) newpostdate,
    COUNT(DISTINCT created) newpost,
    COUNT(DISTINCT closed) closedpost,
    (SELECT 
            COUNT(DISTINCT closed)
        FROM
            tickets
        WHERE
            closed IS NOT NULL
                AND (sent = 0 OR sent = 1)
                AND created >= DATE(NOW()) - INTERVAL 7 DAY
        GROUP BY DATE(created)) solvedpost
FROM
    tickets
WHERE
    created >= DATE(NOW()) - INTERVAL 7 DAY
GROUP BY DATE(created);

1 个答案:

答案 0 :(得分:0)

使用条件聚合:

SELECT 
    DATE(created) newpostdate,
    COUNT(DISTINCT created) newpost,
    COUNT(DISTINCT closed) closedpost,
    COUNT(DISTINCT
        CASE WHEN closed IS NOT NULL AND (sent = 0 OR sent = 1)
        THEN closed END
    ) solvedpost
FROM
    tickets
WHERE
    created >= DATE(NOW()) - INTERVAL 7 DAY
GROUP BY DATE(created);

您甚至不需要closed IS NOT NULL条件,因为NULL不会被计算在内。

这是基于您的原始查询。但我认为你不应该使用DISTINCT。如果您决定不使用DISTICT,则您的查询可能是:

SELECT 
    DATE(created) newpostdate,
    COUNT(created) newpost,
    COUNT(closed) closedpost,
    SUM(closed IS NOT NULL AND (sent = 0 OR sent = 1)) solvedpost
FROM
    tickets
WHERE
    created >= DATE(NOW()) - INTERVAL 7 DAY
GROUP BY DATE(created);