如何将count列添加到查询中?

时间:2017-06-25 12:19:46

标签: sql postgresql

我有一个查询

WITH a as (
SELECT
      SECTION
    , MAX(PRICE) over w
    , MIN(PRICE) over w
    , AVG(PRICE) over w
    , TIME t, price
    , case when MAX(PRICE) over w = price then TIME end maxt
    , case when MIN(PRICE) over w = price then TIME end mint
FROM s154
WINDOW w as (partition by section)
)
select DISTINCT
      SECTION
    , MAX
    , MIN
    , AVG
    , max(maxt) over (partition by section)
    , min(mint) over (partition by section)
from a;

我决定通过在WITH:

中添加新列来修改我的表
count(*) FROM s154 GROUP BY section.

但是添加group by子句也要求组中的max和min。是否可以在WITH部分查询中计算部分?

1 个答案:

答案 0 :(得分:4)

您只需添加count(*) over w

即可
WITH s as (
      SELECT SECTION, MAX(PRICE) over w as max_price,
             MIN(PRICE) over w as min_price, AVG(PRICE) over w as avg_price, 
             TIME as t, price,
             (case when MAX(PRICE) over w = price then TIME end) as maxt
             (case when MIN(PRICE) over w = price then TIME end) as mint,
             (COUNT(*) over w) as cnt
      FROM s154 WINDOW w as (partition by section)
     )
select DISTINCT SECTION, max_price, min_price, avg_price,
       max(maxt) over (partition by section),
       min(mint) over (partition by section),
       cnt
from s;

我非常确定这个查询可以简化。我添加了一些内容,因此更容易理解:

  • 显式列别名。命名您自己的列,它们很重要。
  • 列别名之前的
  • as,所以我可以知道名称的位置。
  • 有意义的CTE名称。 ""在这种情况下毫无意义。至少" s"是表格的缩写。

我认为更简单的版本是:

      SELECT SECTION, MAX(PRICE) as max_price,
             MIN(PRICE) as min_price, AVG(PRICE) as avg_price, 
             (ARRAY_AGG(time ORDER BY price))[1] as time_at_min_price,
             (ARRAY_AGG(time ORDER BY price DESC))[1] as time_at_max_price
      FROM s154 
      GROUP BY section;

这似乎是表达逻辑的更好方法。