我有一张销售表
Date_s sales_man product qty
1-Jan-18 xx 01 30
1-Jan-18 xx 01 20
1-Jan-18 xy 01 20
1-Feb-18 xz 02 10
5-Feb-18 xz 02 30
1-Feb-18 xx 01 10
1-Feb-18 xx 01 40
1-Mar-18 xy 03 20
我希望将以下输出数据格式设为
Product sales_man Jan Feb Mar
01 xx 50 10 0
01 xy 20 0 0
02 xx 0 0 0
02 xy 0 0 0
02 xz 0 0 0
03 xy 0 0 20
答案 0 :(得分:1)
您可以使用聚合。像这样:
select product, salesperson,
sum(case when extract(month from dates) = 1 then qty else 0 end) as jan,
sum(case when extract(month from dates) = 2 then qty else 0 end) as feb
from t
group by product, salesperson;
这使用ANSI SQL日期函数,因为您的数据库标记不清楚。日期操作可能因数据库而异。
此外,在按月查看数据时,通常也要考虑年份(通过过滤或汇总年份)。
答案 1 :(得分:0)
如果您可以更改日期格式,请参阅&1; 1-Jan-18'到' 1-01-18',然后你可以在下面进行
检查sql小提琴
http://sqlfiddle.com/#!9/6d3824/2
如果您考虑以下日期格式 ' 18年1月1日&#39 ;, ' 18年1月1日&#39 ;, ' 18年1月2日&#39 ;;
然后你可以做这个查询
derived
结果
select product, salesman,
sum(case when extract(month from dates) = 1 then qty else 0 end) as jan,
sum(case when extract(month from dates) = 2 then qty else 0 end) as feb
from sales
group by product, salesman;
整个月
http://sqlfiddle.com/#!9/6d3824/9
为所有人做这样的查询,
product salesman jan feb
1 xx 30 0
1 xz 0 20
2 xy 10 0
结果将是
select product, salesman,
sum(case when extract(month from dates) = 1 then qty else 0 end) as jan,
sum(case when extract(month from dates) = 2 then qty else 0 end) as feb,
sum(case when extract(month from dates) = 3 then qty else 0 end) as mar,
sum(case when extract(month from dates) = 4 then qty else 0 end) as apr,
sum(case when extract(month from dates) = 5 then qty else 0 end) as may,
sum(case when extract(month from dates) = 6 then qty else 0 end) as jun,
sum(case when extract(month from dates) = 7 then qty else 0 end) as jul,
sum(case when extract(month from dates) = 8 then qty else 0 end) as aug,
sum(case when extract(month from dates) = 9 then qty else 0 end) as sep,
sum(case when extract(month from dates) = 10 then qty else 0 end) as oct,
sum(case when extract(month from dates) = 11 then qty else 0 end) as nov,
sum(case when extract(month from dates) = 12 then qty else 0 end) as dece
from sales
group by product, salesman;
答案 2 :(得分:0)
如果我的问题正确,你可以尝试:
SELECT * into #TempTable FROM
(select product, salesman, qty, FORMAT(Dates, 'MMM') as Months from sales
) AS s
PIVOT
(
SUM(qty)
FOR Months in (Jan, Feb)
) AS Pvt
select product, salesman, isnull(Jan, 0) as Jan, isnull(Feb, 0) as Feb from
#TempTable order by product
drop table #TempTable