在MSSQL Server中使用PIVOT计数聚合不起作用?

时间:2017-06-13 23:04:38

标签: sql-server-2008 tsql

我正在使用数据透视表来生成交叉制表报告,以使用MSSQL Server汇总数据。但是,当我运行查询时,它没有产生我期望的结果。

这是sql pivot查询:

    select Station, 
       [1] as Good,
       [3] as Bad,
       [5] as Deactivated,
       [6] as Deleted
       --StateCount
from
(
select m.MetaData1 as Station,
       t.ID,
       --m.StateID,
       count(t.[State]) as StateCount
from MasterTags m inner join TagStates t on t.ID = m.StateID
where (m.MetaData1 is not null and m.MetaData1 != '') and (m.PIServerID = 1)
group by m.MetaData1, t.ID, m.StateID, t.[State]
) as result
PIVOT (count(result.StateCount) for ID in ([1], [3], [5], [6])) pvt

结果:

Station | Good  | Bad  | Deactivated | Deleted | StateCount
------- +-------+------+-------------+---------+-----------
ABY     |   0   |  0   |     0       |   1     |     4
ABY     |   0   |  1   |     0       |   0     |    18
ABY     |   1   |  0   |     0       |   0     |    40
FTB     |   0   |  1   |     0       |   0     |    10
FTB     |   1   |  0   |     0       |   0     |   121
KIK     |   0   |  1   |     0       |   0     |     1
KIK     |   1   |  0   |     0       |   0     |    45 

我在上面添加了StateCount列,以显示实际的count(t.[State])值。但是,相反,我在最终结果集中为每个列(Good,Bad,Deactivated,Deleted)获得了1的值。我希望StateCount值将是这些列的数据(如下所示)。

预期产出:

Station | Good  | Bad  | Deactivated | Deleted
------- +-------+------+-------------+--------
ABY     |   40  |  18  |     0       |   4
FTB     |  121  |  10  |     0       |   0
KIK     |   45  |   1  |     0       |   0

这是我第一次在表值表达式中使用数据关系运算符。也许我真的不明白如何正确使用它。我的数据透视查询错了吗?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我发现我的sql查询结构不正确,就像我想要返回正确的结果一样。为了达到我想要的输出,这就是我用PIVOT关系运算符用表值表达式编写sql语句的方法。

    select Station, 
       [1] as Good,
       [3] as Bad,
       [5] as Deactivated,
       [6] as Deleted
from
(
select m.MetaData1,
       m.MetaData1 as Station,
       t.ID,
from MasterTags m inner join TagStates t on t.ID = m.StateID
where (m.MetaData1 is not null and m.MetaData1 != '') and (m.PIServerID = 1)
group by m.MetaData1, t.ID
) as result
PIVOT (count(result.MetaData1) for ID in ([1], [3], [5], [6])) pvt

这给了我正确的结果。