例如:我有一个名为Trans的表。共有三列:Date
,Customer
,Sales
:
Date Customer Sales
01/05/14 1 1000
02/05/14 2 5000
03/05/14 3 2500
10/05/14 4 10000
01/12/13 1 25000
02/12/13 2 500
06/12/13 3 1000
31/12/13 4 3000
我希望按日期显示客户销售额:
Customer Sales_2013 Sale_2014
1 25000 1000
2 500 5000
3 1000 2500
4 3000 10000
我已经尝试过我最好的水平但仍在尝试:-(
任何援助将不胜感激。
感谢您的期待。
答案 0 :(得分:2)
对于SQL Server
,以下内容适用,该方法适用于任何TSQL
,可能只需更改CASE WHEN
的{{1}}。请注意,您需要将字段名称RDMS
更改为其他内容,否则您将不可避免地遇到问题。
Date
修改强>
因为你每天都在学习一些新的东西,SELECT Customer,
sum(CASE WHEN datepart(year, Date) = 2013 THEN Sales ELSE 0 END)
As Sales_2013,
sum(CASE WHEN datepart(year, Date) = 2014 THEN Sales ELSE 0 END)
As Sales_2014
FROM Trans
GROUP BY Customer
方法,我知道在PIVOT
中工作,不知道其他任何事情:
SQL Server 2005
请原谅我,如果这不太正确,只需了解SELECT *
FROM
(
SELECT datepart(year,Date) As SlsYear,Customer,Sales
FROM Trans
) As Source
PIVOT
(
sum(Sales)
FOR SlsYear IN ([2013],[2014])
) As Pvt
现在......
根据评论对单独表格进行编辑
您应该只需使用PIVOT
查询即可完成此操作。
UNION ALL
答案 1 :(得分:2)
假设您使用的是Sql Server,您可以使用以下查询
select a.id,
(select sum(sales) from salesData where datepart(year,Date)=2013 and id=a.id) as sales_2013,
(select sum(sales) from salesData where datepart(year,Date)=2014 and id=a.id) as sales_2014
from salesData as a
group by a.id
答案 2 :(得分:0)
create table #t(Date1 date,Customer int,Sales int)
insert into #t (Date1,Customer,Sales) values('01/05/14',1,1000),('02/05/14',2,5000),('03/05/14',3,2500),('10/05/14',4,10000),('01/12/13',1,25000),('02/12/13',2,500),('06/12/13',3,1000),('1/12/13',4,3000)
SELECT *
FROM
(
SELECT datepart(year,date1) as Sales_year,Customer,Sales
FROM #t
) As Source
PIVOT
(
min(Sales)
FOR Sales_year IN ([2013],[2014])
)piv;