我可以查询或不查询吗?

时间:2015-04-09 20:58:12

标签: mysql

我一直试图让查询/子查询为某些统计数据工作但是失败了,所以我从头开始了。我现在可以得到我想要的结果,但它仍然在两个单独的查询中。我对子查询几乎没有经验,但在重新研究之后,我的心告诉我,我应该能够在一个查询中执行此操作。所有信息都在一个表中,但我需要使用两个单独的GROUP BY才能获得正确的数据。我希望有人可以帮助我解决这个问题,或者至少指出我正确的方向......提前致谢

SELECT MONTH(bookADhistory)-1 AS monthNum,
    COUNT(DISTINCT bookIDHistory) AS totalBooks,
    COUNT(DISTINCT CASE WHEN bookDDCHistory = 300 THEN bookIDHistory end) AS breaches
    FROM bookhistory
    JOIN book ON bookID = bookIDHistory
    WHERE bookID = 44
    GROUP BY MONTH (bookADhistory) ORDER BY monthNum;

SELECT MONTH(historyCreated)-1 AS monthNum,
    COUNT(DISTINCT CASE WHEN bookDDCHistory BETWEEN 1 AND 99 THEN bookIDHistory end) AS delays,
    COUNT(DISTINCT CASE WHEN bookDDCHistory = 200 THEN bookIDHistory end) AS extns,
    COUNT(DISTINCT CASE WHEN bookDDCHistory = 100 THEN bookIDHistory end) AS lateClose
    FROM bookhistory
    JOIN book ON bookID = bookIDHistory
    WHERE bookID = 44
    GROUP BY MONTH (historyCreated) ORDER BY monthNum;

1 个答案:

答案 0 :(得分:1)

可能有一些方法可以简化这一点,但是使用你拥有的东西并将它们粘贴在子查询中会看起来像:

SELECT
    *
FROM
    (

        SELECT MONTH(bookADhistory)-1 AS monthNum,
            COUNT(DISTINCT bookIDHistory) AS totalBooks,
            COUNT(DISTINCT CASE WHEN bookDDCHistory = 300 THEN bookIDHistory end) AS breaches
        FROM bookhistory
            JOIN book ON bookID = bookIDHistory
        WHERE bookID = 44
        GROUP BY MONTH (bookADhistory) 
        ORDER BY monthNum
    ) t1
    INNER JOIN
    (

        SELECT MONTH(historyCreated)-1 AS monthNum,
            COUNT(DISTINCT CASE WHEN bookDDCHistory BETWEEN 1 AND 99 THEN bookIDHistory end) AS delays,
            COUNT(DISTINCT CASE WHEN bookDDCHistory = 200 THEN bookIDHistory end) AS extns,
            COUNT(DISTINCT CASE WHEN bookDDCHistory = 100 THEN bookIDHistory end) AS lateClose
        FROM bookhistory
            JOIN book ON bookID = bookIDHistory
        WHERE bookID = 44
        GROUP BY MONTH (historyCreated) 
        ORDER BY monthNum;
    ) t2 ON
        t1.monthNum = t2.monthNum