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 に答える