这里是一个实际应用的例子,一开始的数据是错综复杂的,如下图所示,实际很多月份很多的类型,需要的是得到每个部门不同了类型不同月份的实际金额,这儿就用到了行转列的写法,百度了一下确实有效,成功之后的显示字段确实1,2,3,4....这种的,最好变为january,february...的这种所以就用了声明并赋值加case when 的写法顺便吧null的值变为0;在此做下记录,希望也可以帮到用到的人。
下图的sql是这样子的:(这是一个union al l联立的多个表)
select year(ExpenseDate) as NowYear,ExpenseDept,AccountMonth,ISNULL(AccountMoney,0) as monthmoney,'差旅费' as FYType FROM CW_WY_TravelExpenseBill_M m inner join BPMDB..BPMInstTasks s on m.TaskID = s.TaskID where (s.State='Approved' or s.State='Running')
union all
select year(ExpenseDate)as NowYear,ExpenseDept,AccountMonth,ISNULL(AccountMoney,0) as monthmoney,'日常费用' as FYType FROM CW_WY_DailyLiveExpenseBill_M m inner join BPMDB..BPMInstTasks s on m.TaskID = s.TaskID where (s.State='Approved' or s.State='Running')
union all
select NowYear,deptname,NowMonth,ISNULL(PayMoney,0) as monthmoney,FeiYongType as FYType from CW_WY_DailyLiveExpenseFuKuan_T m inner join BPMDB..BPMInstTasks s on m.TaskID = s.TaskID where (s.State='Approved' or s.State='Running')
要形成下图这样的效果sql需要有所改动:
SELECT NowYear,ExpenseDept,FYType,January=case when [1] is null then 0 else [1] end,February=case when [2] is null then 0 else [2] end,March=case when [3] is null then 0 else [3] end,April=case when [4] is null then 0 else [4] end,May=case when [5] is null then 0 else [5] end,June=case when [6] is null then 0 else [6] end,July=case when [7] is null then 0 else [7] end,August=case when [8] is null then 0 else [8] end,September=case when [9] is null then 0 else [9] end, Octorber=case when [10] is null then 0 else [10] end,November=case when [11] is null then 0 else [11] end,December=case when [12] is null then 0 else [12] end FROM (
select year(ExpenseDate) as NowYear,ExpenseDept,AccountMonth,ISNULL(AccountMoney,0) as monthmoney,'差旅费' as FYType FROM CW_WY_TravelExpenseBill_M m inner join BPMDB..BPMInstTasks s on m.TaskID = s.TaskID where (s.State='Approved' or s.State='Running')
union all
select year(ExpenseDate)as NowYear,ExpenseDept,AccountMonth,ISNULL(AccountMoney,0) as monthmoney,'日常费用' as FYType FROM CW_WY_DailyLiveExpenseBill_M m inner join BPMDB..BPMInstTasks s on m.TaskID = s.TaskID where (s.State='Approved' or s.State='Running')
union all
select NowYear,deptname,NowMonth,ISNULL(PayMoney,0) as monthmoney,FeiYongType as FYType from CW_WY_DailyLiveExpenseFuKuan_T m inner join BPMDB..BPMInstTasks s on m.TaskID = s.TaskID where (s.State='Approved' or s.State='Running')
) /*数据源*/
AS P
PIVOT
(
SUM(monthmoney/*行转列后 列的值*/) FOR
p.AccountMonth/*需要行转列的列*/ IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]/*列的值*/)
) AS T
主要是两个知识点:行转列的写法和case when 的用法。仅为借鉴,如有错误请指教。