一个`Select`查询生成12个结果集

时间:2014-09-22 07:02:30

标签: mysql sql database select

我有一张名为VAT的表格,我需要生成每月增值税报告。以下是我的所作所为......

    SELECT SUM(Amount) AS "January" 
    WHERE current_time_stamp BETWEEN '2014-01-01' AND '2014-01-310'
    FROM VAT

就像上面的查询一样,我对1月,2月,3月等有12个查询。所以,有没有一种方法可以在1个查询中获得所有这些?

4 个答案:

答案 0 :(得分:1)

您可以将条件和与case语句一起使用,下面的查询将为您提供一行,其中包含12列,每个月的总和

SELECT 
   SUM(case when current_time_stamp BETWEEN '2014-01-01' AND '2014-01-31' then Amount else 0 end) AS `January` ,
   SUM(case when current_time_stamp BETWEEN '2014-02-01' AND '2014-02-29' then Amount else 0 end) AS `Febuary` ,
   .
   .
   .
   SUM(case when current_time_stamp BETWEEN '2014-12-01' AND '2014-12-31' then Amount else 0 end) AS `December` 
 FROM VAT

答案 1 :(得分:0)

使用GROUP BY,如下所示:

SELECT SUM(Amount), MONTH(current_time_stamp) AS `Month` 
FROM VAT
WHERE current_time_stamp BETWEEN '2014-01-01' AND '2014-12-31'
GROUP BY MONTH(current_time_stamp)

但是,如果您有大量记录,可能会很慢。

答案 2 :(得分:0)

类似于扩展到十二个月的事情

SELECT MAX(X.January) AS January, MAX(X.February) AS February FROM
(
SELECT SUM(Amount) AS January, 0 AS February
    WHERE current_time_stamp BETWEEN '2014-01-01' AND '2014-01-31'
    FROM VAT
UNION
SELECT 0 AS January, SUM(Amount) AS February
    WHERE current_time_stamp BETWEEN '2014-02-01' AND '2014-02-29'
    FROM VAT
) X

或者你也可以这样做:

SELECT 'January' AS Month, SUM(Amount) AS Amount
    WHERE current_time_stamp BETWEEN '2014-01-01' AND '2014-01-31'
    FROM VAT
UNION
 SELECT 'February' AS Month, SUM(Amount) AS Amount
    WHERE current_time_stamp BETWEEN '2014-02-01' AND '2014-02-29'
    FROM VAT

答案 3 :(得分:0)

select t.mnth_amt,t.mnth 
from (
     select sum(amount) as mnth_amt,MONTH(current_time_stamp ) as mnth from vat where current_time_stamp BETWEEN '2014-01-01' AND  
     '2014-12-31' GROUP BY MONTH(current_time_stamp) 
     ) t order by mnth