如何转动简单的连接数据集?

时间:2012-11-23 22:45:50

标签: sql sql-server sql-server-2008 tsql

我有这个问题:

select MONTH(x.status_date) m
, YEAR(x.status_date) y
from [XREF_WET_MASTER] x
join F_ACCESSION_DAILY f
on x.accession_id=f.accession_id
pivot (count(*) for f.REQUISITION_TYPE in ([req1],[req2],[req3])
) as CountofThatTypeofReq

我收到此错误:

  

'*'附近的语法不正确。

count(*)

这是预期的结果:

+---+------+------+------+------+
| m |  y   | req1 | req2 | req3 |
+---+------+------+------+------+
| 1 | 2010 |   34 |    3 |    6 |
| 2 | 2010 |   56 |    6 |    0 |
| 3 | 2010 |    5 |   33 |    4 |
+---+------+------+------+------+

对于这个支点的任何指导,我将非常感激!

2 个答案:

答案 0 :(得分:2)

而不是count(*),您应该能够使用以下内容:

select *
from
(
  select MONTH(x.status_date) m
    , YEAR(x.status_date) y
    , f.REQUISITION_TYPE
    , f.accession_id
  from [XREF_WET_MASTER] x
  join F_ACCESSION_DAILY f
    on x.accession_id=f.accession_id
) src
pivot 
(
  count(REQUISITION_TYPE) 
  for REQUISITION_TYPE in ([req1],[req2],[req3])
) as CountofThatTypeofReq

答案 1 :(得分:1)

根据文档,它不是计数(*),而是appear you need to specify a specific column可以转动,所以请尝试:

select MONTH(x.status_date) m
, YEAR(x.status_date) y
from [XREF_WET_MASTER] x
join F_ACCESSION_DAILY f
on x.accession_id=f.accession_id
pivot (count(f.accession_id) for f.REQUISITION_TYPE in ([req1],[req2],[req3])
) as CountofThatTypeofReq

......或类似的东西。