SQL查询摘要问题

时间:2017-04-01 09:13:31

标签: mysql totals

我是SQL的新手,并尝试创建一个有效的SQL查询的总摘要。它列出了一个月数据的总结果。 现在我需要查询结果的总值。 所以我在查询中创建了一个查询' SQL的一部分,但它因为我缺乏SQL知识而无法正常工作。我想这对你来说很容易解决: - )

每天结果为一个月的工作SQL查询:

SELECT
          DATE_FORMAT(date, '%d/%m/%y') AS Datum,
          COUNT(*) AS Berichten,
          SUM(CASE WHEN virusinfected>0 THEN 1 ELSE 0 END) AS Virus,
          SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND isspam>0 THEN 1 ELSE 0 END) AS Ongewenst,
          SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND (isspam=1) AND isrblspam>0 THEN 1 ELSE 0 END) AS RBL,
          SUM(size) AS Grootte
         FROM
          maillog
         WHERE
          1=1
        AND (1=1)
        AND
         date < '2017-04-01'
        AND
         date >= '2017-03-01'
        AND
         to_domain = 'domain1.nl'
        OR
        date < '2017-04-01'
        AND
         date >= '2017-03-01'
        AND
         to_domain = 'domain2.nl'

         GROUP BY
          Datum
         ORDER BY
          date

尝试创建月总计的错误查询:

SELECT  Datum,
    SUM(Berichten) AS Berichten,
    SUM(Virus) AS Virus,
    SUM(Ongewenst) AS Ongewenst,
    SUM(RBL) AS RBL,
    SUM(Grootte) AS Grootte,
    FROM    (   SELECT
                  DATE_FORMAT(date, '%d/%m/%y') AS Datum,
                  COUNT(*) AS Berichten,
                  SUM(CASE WHEN virusinfected>0 THEN 1 ELSE 0 END) AS Virus,
                  SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND isspam>0 THEN 1 ELSE 0 END) AS Ongewenst,
                  SUM(CASE WHEN (virusinfected=0 OR virusinfected IS NULL) AND (isspam=1) AND isrblspam>0 THEN 1 ELSE 0 END) AS RBL,
                  SUM(size) AS Grootte
                 FROM
                  maillog
                 WHERE
                  1=1
                AND (1=1)
                AND
                 date < '2017-04-01'
                AND
                 date >= '2017-03-01'
                AND
                 to_domain = 'domain1.nl'
                OR
                date < '2017-04-01'
                AND
                 date >= '2017-03-01'
                AND
                 to_domain = 'domain2.nl'

                 GROUP BY
                  Datum
                 ORDER BY
                  date
            ) t
    GROUP BY Datum;

提前致谢。

1 个答案:

答案 0 :(得分:0)

只需在第一个SQL语句中添加一些内容即可完成所需:在group by子句后添加with rollup

GROUP BY Datum WITH ROLLUP

它将比带有子查询的版本更有效地运行,尽管它可以这样工作,但是你应该删除外部group by子句而不是选择Datum,因为你不要要求每个日期的总数,但总体而言。

但是,您将丢失详细信息,然后才能获得总计。您必须使用与原始查询的联合来获取两个级别的总计。您可以想象with rollup修饰符可以更有效地完成工作。