1

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

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

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

SQL小提琴链接

4

2 回答 2

2

你不需要HAVING这个。就像GROUP BY "timestamp"这样WHERE "active" = 1

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

更新的 SQL Fiddle 演示

于 2012-11-15T11:57:24.287 回答
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 本身中应用您的过滤器。

演示

于 2012-11-15T11:57:34.560 回答