如何通过分组行来转动行?

时间:2012-06-27 09:56:18

标签: sql-server pivot

我有查询显示如下表:
enter image description here

但我希望PIVOTbulan和表格结果分组,如下所示:
enter image description here

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

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]

2 个答案:

答案 0 :(得分: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

在这里你必须添加与组数一样多的连接条件。

答案 1 :(得分: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