透视数据的数量

时间:2014-01-06 11:07:34

标签: sql database sql-server-2008-r2

我有以下数据:

Cod# prodotto     Mon

  A               Jan

  B               Feb

  C               Jan

  D               Feb

  A               Jan

  D               Jan

  D               Jan

我希望将数据作为特定月份分组的Cod#prodotto数量,如下所示:

Cod# prodotto   Jan  Feb 

   A             2    -

   B             -    1

   C             1    -

   D             2    1

我将查询作为:

select * from
(
select CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100) as Month , [Cod# prodotto] as col1,count([Cod# prodotto]) as codprodotto
from dbPratiche
where  [Cod# prodotto] is not null
and [Data OUT (No Val#Vuoto)] < CONVERT(datetime,'2012/01/11')
and Stato='OUT ATTIVATA' or Stato='SOSPESA' 
group by ([Cod# prodotto]),CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100)

) T

pivot
(
  count(codprodotto)
  for Month 
  in([nov],[dec],[jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct])
) P

还应用以下方法:

select * from
(
select 1 CntCol,CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100) as Month , [Cod# prodotto] as col1
from dbPratiche
where  [Cod# prodotto] is not null
and [Data OUT (No Val#Vuoto)] < CONVERT(datetime,'2012/01/11')
and Stato='OUT ATTIVATA' or Stato='SOSPESA' 
group by ([Cod# prodotto]),CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100)

) T

pivot
(
  sum(CntCol)
  for Month 
  in([nov],[dec],[jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct])
) P

但它给了我错误的结果。

请帮帮我。

2 个答案:

答案 0 :(得分:1)

将您的第一个查询更改为:

select * from
(
select CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100) as Month , [Cod# prodotto] as col1,count([Cod# prodotto]) as codprodotto
from dbPratiche
where  [Cod# prodotto] is not null
and [Data OUT (No Val#Vuoto)] < CONVERT(datetime,'2012/01/11')
and Stato='OUT ATTIVATA' or Stato='SOSPESA' 
group by ([Cod# prodotto]),CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100)

) T

pivot
(
  SUM(codprodotto)
  for Month 
  in([nov],[dec],[jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct])
) P

我已将Pivot函数从count更改为sum。看起来它应该可行。

答案 1 :(得分:0)

也通过以下方式完成:

select * from
(
select 1 CntCol,CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100) as Month , [Cod# prodotto] as col1
from dbPratiche
where  [Cod# prodotto] is not null
and [Data OUT (No Val#Vuoto)] < CONVERT(datetime,'2012/01/11')
and Stato='OUT ATTIVATA' or Stato='SOSPESA' 
) T

pivot
(
  sum(CntCol)
  for Month 
  in([nov],[dec],[jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct])
) P

但@ simon的答案看起来更正确,因为他在此查询中添加CntCol时没有添加额外的列。