0

我有查询显示这样的表:
在此处输入图像描述

但我想PIVOT通过分组bulan和表格结果来做到这一点:
在此处输入图像描述

这是我用来获取当前结果的查询:

SELECT 
    month([date]) as bulan, 
    [type] as tipe,
    SUM([net qty]) total_karton, 
    CAST(SUM([cm1 (rp)]) as decimal) as total_uang
FROM 
    tbl_weeklyflash_ID
WHERE
    DATEDIFF(month,[date],CURRENT_TIMESTAMP) between 0 and 2
GROUP BY 
    month([date]),
    [type]
ORDER BY 
    month([date]), [type]
4

2 回答 2

1

如果每组的行数是动态的,但组数总是 3,那么试试这个代码

;with maintable as (select month([date]) m_date,row_number() over(order by count(*) desc) row_num from tbl_weeklyflash_ID WHERE DATEDIFF(month,[date],CURRENT_TIMESTAMP) between 0 and 2
group by month([date])),
t1 as ( select month([date]) as bulan, [type] as tipe,SUM([net qty]) total_karton, CAST(SUM([cm1 (rp)]) as decimal) as total_uang,row_number() over(order by month([date])) as slno  from tbl_weeklyflash_ID where month([date]) =(select m_date from maintable where row_num=1) GROUP BY month([date]), [type]) ,
t2 as ( select month([date]) as bulan, [type] as tipe,SUM([net qty]) total_karton, CAST(SUM([cm1 (rp)]) as decimal) as total_uang,row_number() over(order by month([date])) as slno  from tbl_weeklyflash_ID where month([date]) =(select m_date from maintable where row_num=2) GROUP BY month([date]), [type]),
t3 as ( select month([date]) as bulan, [type] as tipe,SUM([net qty]) total_karton, CAST(SUM([cm1 (rp)]) as decimal) as total_uang,row_number() over(order by month([date])) as slno  from tbl_weeklyflash_ID where month([date]) =(select m_date from maintable where row_num=3) GROUP BY month([date]), [type])
select t1.tipe,t1.total_karton [karton1],t1.total_uang [uang1],t2.total_karton [karton2],t2.total_uang [uang2],t3.total_karton [karton3],t3.total_uang [uang3]
from t1 full outer join t2
on t1.slno=t2.slno 
full outer join t3
on t2.slno =t3.slno 
于 2012-07-03T09:25:10.943 回答
1

这不是确切的解决方案。如果每组的行数始终如示例所示(本示例为 5),则可以执行以下操作。

declare @row_count int =6;
    with cte as(
        select  month([date]) as bulan, 
        [type] as tipe,
        SUM([net qty]) total_karton, 
        CAST(SUM([cm1 (rp)]) as decimal) as total_uang,row_number() over(order 
    by month([date]),[type]) as rnk 
        from tbl_weeklyflash_ID 
        WHERE
        DATEDIFF(month,[date],CURRENT_TIMESTAMP) between 0 and 2
        GROUP BY 
        month([date]),
        [type]
        )
    select * from cte T1 join cte T2 
    on T1.rnk= T2.rnk-@row_count 
    and t1.rnk between 1 and @row_count
    join cte T3
    on  T2.rnk= T3.rnk-@row_count 
    and t2.rnk between 1*@row_count+1 and 2*@row_count

在这里,您必须添加与组数一样多的加入条件..

于 2012-06-27T10:55:14.497 回答