我怎样才能在同一份声明中显示jan,4月2日的销售情况?

时间:2014-08-14 19:50:04

标签: sql sql-server

我正在尝试制作一份能够并排显示销售情况的报告,但每张纸只能获得一个月,这就是我现在所拥有的。

select c.[AR CUST Customer ID],c.[AR CUST Name], sum([AR SALE Subtotal]) as Jan_2013_Sales
from [AR Customer] c
 join [AR Sales] s
  on c.[AR CUST Customer ID]=s.[AR SALE Customer ID]
where [AR SALE Date] >= '1-01-2013' and [AR SALE Date] < '2-01-2013' and [AR SALE Document Type] like 'invoice'
group by c.[AR CUST Customer ID],c.[AR CUST Name]
order by [AR CUST Customer ID]

目前这是我得到的输出:

AR Cust Customer ID   |   AR Cust Name  |   Jan_2013_Sales

040891                |    Dans         |      268.8

041473                |    Dicks        |       2846.74

哪个没问题,但我希望能够从同一个Query中得到:

AR Cust Customer ID   |   AR Cust Name  |   Jan_2013_Sales |  Feb_2013_Sales

040891                |    Dans         |       268.8      |     354.54

041473                |    Dicks        |       2846.74    |     1564.53

2 个答案:

答案 0 :(得分:0)

您必须在SELECT STATEMENT

中每个月使用IF或CASE语句
 SUM (IF( (AR SALE DATE >= 'START DATE January ' AND AR SALE DATE <= 'END DATE Jan '),AR SALE Subtotal, 0) as 'Jan SALE' ,  SUM (IF( (AR SALE DATE  >= 'START DATE FEB ' AND AR SALE DATE <= 'END DATE FEB '),AR SALE Subtotal, 0) as 'FEB SALE'

删除where子句。  如果你有小提琴日期,它将有助于编写整个查询。

答案 1 :(得分:0)

如果您确切知道要运行此报告的月份,您可以这样做......

select c.[AR CUST Customer ID],c.[AR CUST Name], jan.sumJan, feb.sumfeb, march.sumMarch
from [AR Customer] c
 left join (select [AR SALE Customer ID], sum([AR SALE Subtotal]) as sumJan from [AR Sales]
        where [AR SALE Date] >= '1-01-2013' and [AR SALE Date] < '2-01-2013' and [AR SALE     Document Type] like 'invoice'
        group by [AR SALE Customer ID]) jan on jan.[AR SALE Customer ID] = c.[AR CUST Customer ID]
 left join (select [AR SALE Customer ID], sum([AR SALE Subtotal]) as sumFeb from [AR Sales]
        where [AR SALE Date] >= '2-01-2013' and [AR SALE Date] < '3-01-2013' and [AR SALE     Document Type] like 'invoice'
        group by [AR SALE Customer ID]) Feb on Feb.[AR SALE Customer ID] = c.[AR CUST Customer ID]
 left join (select [AR SALE Customer ID], sum([AR SALE Subtotal]) as sumMarch from [AR Sales]
        where [AR SALE Date] >= '3-01-2013' and [AR SALE Date] < '4-01-2013' and [AR SALE     Document Type] like 'invoice'
        group by [AR SALE Customer ID]) March on March.[AR SALE Customer ID] = c.[AR CUST Customer ID]
order by [AR CUST Customer ID]

否则,您需要一个数据透视表,这里是codeProject.com上的example