首页 新闻 会员 周边 捐助

sql server日期行转列

0
悬赏园豆:20 [待解决问题]

DECLARE @StarDate varchar(50),@EndDatevarchar(50)
DECLARE @MC varchar(6),@FAC int
set @StarDate='2019-02-25 08:00:00'
set @EndDate='2019-03-25 07:59:59'
set @MC='2000'
set @FAC=8

with tempb AS (
select convert(varchar(100),p.SaveDate,112) as DayTime ,isnull(sum(p.NetWeight/1000),0) as NetWeight,c.CustomerId
from Base_PoundRecord p
left join Base_Customers c on c.CustomerId=p.CustomerId
where p.CRState = 9 AND (p.SaveDate BETWEEN @StarDate and @EndDate) AND p.FactoryId=@FAC and p.MaterialCode=@MC and c.IsFinancial=1 and c.DeleteMark=1
group by SaveDate,p.NetWeight,c.CustomerId
)
SELECT CustomerId,DayTime,NetWeight FROM tempb

--卡住的位置
PIVOT (sum(NetWeight) as NetWeight FOR DayTime in(这里不知道该如何去构造日期))

查询后得到的结果是
CustomerId NetWeight DayTime
XXXXXXXX 31 2019-02-25 08:15:12
XXXXXXXX 32 2019-02-25 09:45:21
XXXXXXXX 31.2 2019-02-26 10:14:17
XXXXXXXX 33.1 2019-02-26 13:51:11
XXXXXXXX 34.1 2019-02-27 16:43:08
BBBBBBBB 32 2019-02-25 09:45:21
BBBBBBBB 32 2019-02-25 09:45:21
XXXXXXXX 32 2019-02-28 09:45:21
CCCCCCC 32 2019-02-25 09:45:21
CCCCCCC 32 2019-02-25 09:45:21
DDDDDDD 32 2019-02-25 09:45:21
DDDDDDD 32 2019-02-25 09:45:21
BBBBBBB 32 2019-02-26 09:45:21

想要得到的结果是,那一天没有的用0替代
CustomerId 2019-02-25 2019-02-26 2019-02-27 2019-02-28..........2019-03-25
XXXXXXXX 63 64.3 34.1 32 0
BBBBBBBB 64 32 0 0 0
CCCCCCC 64 0 0 0 0
DDDDDDD 64 0 0 0 0

尽量能够让SQL运行效率高些

wavegui的主页 wavegui | 初学一级 | 园豆:80
提问于:2019-03-29 16:15
< >
分享
所有回答(2)
0

问题自己解决

wavegui | 园豆:80 (初学一级) | 2019-04-02 06:58

PIVOT (sum(NetWeight) as NetWeight FOR DayTime in(这里不知道该如何去构造日期))
楼主你好。如果是日期的话,最后括号部分是如何处理的?

支持(0) 反对(0) 码里奥 | 园豆:202 (菜鸟二级) | 2021-11-01 14:42
0

正常查询

行列互换的查询结果

fuyouqiang | 园豆:206 (菜鸟二级) | 2020-05-22 17:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册