t-sql在聚合列上进行透视

时间:2013-10-15 15:32:36

标签: sql-server tsql pivot

我已经查看了与枢轴相关的查询,但似乎找不到与我想做的匹配的查询。我有一张表如下: -

type  |  iscurrent
-----------------
A     |  1
A     |  1
A     |  0
B     |  1
B     |  1
B     |  1
C....

我想透过这些数据进行调整,使其如下所示, iscurrent 字段只会包含0和1。

TYPE  |  1  |  0
-----------------
A     |  2  |  1
B     |  3  |  0
C     | ...

我到目前为止的代码是

SELECT loadid, '1', '0'
FROM (
SELECT iscurrent, loadid
FROM #table) up
PIVOT (sum(iscurrent) FOR iscurrent IN ([1], [0])) AS pvt
ORDER BY loadid
GO

当我尝试运行代码时出现一点操作数错误?

1 个答案:

答案 0 :(得分:1)

尝试

SELECT loadid, [1], [0]

PIVOT (count(isCurrent) FOR iscurrent IN ([1], [0])) AS pvt

即:

SELECT loadid, [1],[0]
FROM (  SELECT iscurrent, loadid FROM #table) up
PIVOT (count(iscurrent) FOR iscurrent IN ([1], [0])) AS pvt
ORDER BY loadid