不使用group by对行进行分组

时间:2014-08-20 09:48:37

标签: sql sql-server sql-server-2005

我为一些数据构建了一个SQL小提琴,并且更清楚我想要什么。

http://sqlfiddle.com/#!3/076406/2

我的查询是

SELECT c1.ID 
,c1.Value Ian
,c2.Value Feb
,c3.Value Mar
,c4.Value Apr 
,c5.Value Mai 
,c6.Value Iun
,c7.Value Iul
,c8.Value Aug
,c9.Value Sept
,c10.Value Oct
,c11.Value Noe
,c12.Value Dec
 FROM A a
left outer join B as c1 on a.ID=c1.IDA and MONTH(a.ADate) = 1
left outer join B as c2 on a.ID=c2.IDA and MONTH(a.ADate) = 2
left outer join B as c3 on a.ID=c3.IDA and MONTH(a.ADate) = 3
left outer join B as c4 on a.ID=c4.IDA and MONTH(a.ADate) = 4
left outer join B as c5 on a.ID=c5.IDA and MONTH(a.ADate) = 5
left outer join B as c6 on a.ID=c6.IDA and MONTH(a.ADate) = 6
left outer join B as c7 on a.ID=c7.IDA and MONTH(a.ADate) = 7
left outer join B as c8 on a.ID=c8.IDA and MONTH(a.ADate) = 8
left outer join B as c9 on a.ID=c9.IDA and MONTH(a.ADate) = 9
left outer join B as c10 on a.ID=c10.IDA and MONTH(a.ADate) = 10
left outer join B as c11 on a.ID=c11.IDA and MONTH(a.ADate) = 11
left outer join B as c12 on a.ID=c11.IDA and MONTH(a.ADate) = 12
WHERE YEAR(a.ADate) = 2014  

因此,如果您运行此小提琴,您将获得此类数据

ID   Ian   Feb  Mar  Apr ..
1    10   NULL NULL NULL
2    10   NULL NULL NULL 
3    10   NULL NULL NULL
4    10   NULL NULL NULL 
5    10   NULL NULL NULL
6    10   NULL NULL NULL 
7    10   NULL NULL NULL
8    10   NULL NULL NULL 
NULL NULL  9   NULL NULL
NULL NULL  9   NULL NULL 
NULL NULL  9   NULL NULL
NULL NULL  9   NULL NULL 
NULL NULL  9   NULL NULL
NULL NULL  9   NULL NULL 
NULL NULL  9   NULL NULL
NULL NULL  9   NULL NULL 

依旧......我想建立一个像

这样的表
ID   Ian   Feb  Mar  Apr ..
1    10     9   8    6
2    10     9   8    5
3    10     9   8    6
4    10     9   7    5 
5    10     9   7    6
6    10     9   8    5 
7    10     9   8    6
8    10     9   7    5 

我怎样才能获得这个结果?我很无能为力......任何帮助都会很好。此外,查询必须在sql server 2005上运行。

对于表A中的每个ID,我将在表B中总是有8个值,我想以某种方式将它们组合在一起,因此我的结果表应该有8行和13列。对于表B中的每个ID和表A中的每个ID,列+ ID列。

希望现在很清楚。

1 个答案:

答案 0 :(得分:1)

使用PIVOT

尝试此操作
SELECT 
   ID, 
   [1] as Ian, 
   [2] as Feb, 
   [3] as Mar, 
   [4] as Apr,
   [5] as Mai,
   [6] as Iun,
   [7] as Iul,
   [8] as Aug,
   [9] as Sept,
   [10] as Oct,
   [11] as Noe,
   [12] as Dec
FROM b
PIVOT
(
   SUM(Value) 
   FOR IDA IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
)  AS ResultTable

请参阅DEMO

PIVOT和UNPIVOT用于升级到SQL Server 2005或更高版本的数据库。