结合min()和()

时间:2012-11-15 11:49:11

标签: tsql

是否有可能在having()聚合内联中使用linke min()

select distinct
  "timestamp"
  , MinActiveValue = min( "value" ) over ( partition by "timestamp" ) having ( "active" = 1 )
from
  "data"

在下面的链接示例中,使用第一个查询可以很好地工作。 实际上,我不想为min-condition使用where子句,因为我会破坏同一查询中使用的数据过滤。 (例如,有一些分组总和由同一查询计算)

SQL Fiddle Link

2 个答案:

答案 0 :(得分:2)

您不需要HAVING。只需GROUP BY "timestamp" WHERE "active" = 1就像这样:

SELECT
  "timestamp"
  , MinActiveValue = MIN( "value" )
FROM  "data"
WHERE "active" = 1
GROUP BY "timestamp";

Updated SQL Fiddle Demo

答案 1 :(得分:1)

也许这就是:

WITH CTE AS
(
   SELECT DISTINCT
      timestamp
    , active
    , value
    , RN = ROW_NUMBER() OVER ( PARTITION BY timestamp ORDER BY active DESC,value ASC )
  FROM
    data
)
SELECT timestamp, value AS MinActiveValue
FROM CTE
WHERE RN = 1 AND active = 1

您可以在此处将过滤器应用于CTE本身。

Demo