这是我的表:
Company Year CustomerCount1 CustomerCount2
1 2010 100 150
1 2011 120 130
1 2012 300 140
2 2010 50 90
2 2011 45 110
2 2012 60 120
CustomerCount1是年初的客户数量 CustomerCount2是一年中的客户数量 如何运行查询来获得这样的输出
Company Year2010 Year2012
1 100 140
2 50 120
其中
100是company1的2010年CustomerCount1
140是company1的2012年CustomerCount2
50是2010年的companyC的CustomerCount1
120是2012年的CustomerCount2 for company2
答案 0 :(得分:1)
似乎您的数据结构可以使用一些规范化。但是你可以很容易地使用条件聚合来做这样的事情。
declare @Something table
(
Company int
, Year int
, CustomerCount1 int
, CustomerCount2 int
)
insert @Something
values
(1, 2010, 100, 150)
, (1, 2011, 120, 130)
, (1, 2012, 300, 140)
, (2, 2010, 50, 90)
, (2, 2011, 45, 110)
, (2, 2012, 60, 120)
select Company
, max(case when Year = 2010 then CustomerCount1 end) as Year2010
, max(case when Year = 2012 then CustomerCount2 end) as Year2012
from @Something
where Year in (2010, 2012)
group by Company