如何通过表达式进行分区

时间:2015-02-04 19:08:48

标签: sql sql-server-2008

我想用表达式而不是字段进行分区。采取此查询

SELECT 
      ID,
      Value,
      Status,
      SUM(Value) OVER(PARTITION BY ID) AS "Sum",
      COUNT(*) OVER(PARTITION BY ID, Status = 'Ready') AS ReadyCount --Error here
FROM TestAggregation

我需要获取分组状态的ReadyCount,但只需要将计数应用于已准备好的状态。这可能吗?

1 个答案:

答案 0 :(得分:3)

您可以改为使用条件总和:

SELECT 
      ID,
      Value,
      Status,
      SUM(Value) OVER(PARTITION BY ID) AS "Sum",
      SUM(CASE WHEN Status = 'Ready' THEN 1 ELSE 0 END) OVER(PARTITION BY ID) AS ReadyCount --Error here
FROM TestAggregation