2017-03-02 11 views
-1

私は、MS SQL Serverのピボットテーブル

select month(createdatetime) as month, 
     year(createdatetime) as year, 
     count(*) as members 
from [toneexcel].[dbo].[teUserMemberSIMAcc] 
where year(createdatetime) > '2015' and status = 'AC' 
group by month(createdatetime), year(createdatetime) 
order by year(createdatetime), month(createdatetime) 

が私を提案してください、この次のクエリで年間のピボットデータのTQ

を探して

電流出力は

Month| year | members 
----------------------- 
1 2016 12914 
2 2016 13338 
3 2016 13633 
4 2016 11110 
5 2016 9868 
6 2016 7088 
7 2016 6785 
8 2016 8260 
9 2016 8386 
10 2016 8506 
11 2016 7187 
12 2016 7976 
1 2017 8535 
2 2017 12744 
3 2017 579 

期待されています出力は

Month | 2016 | 2017 
---------------------- 
1  12914 | 8535 
2  13338 12744 
3  13633 579 
4  11110 
5  9868 
6  7088 
7  6785 
8  8260 
9  8386 
10  8506 
11  7187 
12  7976 
+0

サンプルデータとあなたの期待される出力を示してください。 –

+0

サンプルデータをいくつか与える。 –

+0

@madhanはコメントではなく質問自体にデータを投稿します。あなたが投稿したものは役に立ちません - それは単なる数字の行です。あなたは1年に1列、1ヶ月に1つ、何を望みましたか? *該当する情報で質問を更新してください。私はあなたのためにそれをやろうとしていますが、データがどのように見えているのかわかりません。 –

答えて

0

サンプルのデータと期待される出力に従って。あなたはこれを考慮することができます。使用方法:PIVOT

;with cte as (
select 1 as Month,2016 as Year,12914 as Members union 
select 2 as Month,2016 as Year,13338 as Members union 
select 3 as Month,2016 as Year,13633 as Members union 
select 4 as Month,2016 as Year,11110 as Members union 
select 5 as Month,2016 as Year,9868 as Members union 
select 6 as Month,2016 as Year,7088 as Members union 
select 7 as Month,2016 as Year,6785 as Members union 
select 8 as Month,2016 as Year,8260 as Members union 
select 9 as Month,2016 as Year,8386 as Members union 
select 10 as Month,2016 as Year,8506 as Members union 
select 12 as Month,2016 as Year,7187 as Members union 
select 1 as Month,2017 as Year,8535 as Members union 
select 2 as Month,2017 as Year,12744 as Members union 
select 3 as Month,2017 as Year,579 as Members 

) 
select * from (
select * 
from cte 
)t 
pivot (
max (members) 
for year in ([2016],[2017]) 
) 
as pvt; 

0
select [Month], isnull([2016],0) [2016],isnull([2017],0) [2017] 
from 
(
    select * 
    from #Table1 
) src 
pivot 
(
    max([members]) 
    for [year] in ([2016], [2017]) 
) piv; 

OR

SELECT MONTH,MAX(CASE WHEN YEAR=2016 THEN MEMBERS ELSE '' END) [2016], 
MAX(CASE WHEN YEAR=2017 THEN MEMBERS ELSE '' END) [2017] FROM #Table1 
GROUP BY MONTH