TotalCount基于仍需要获取的列

时间:2018-02-23 08:04:02

标签: sql postgresql

考虑到下面的获取行,我还需要总计 id-token 对有 valuableField 的方式。 valuableField中的值可能有重复

字段

id - 表格列

token - 表格列

valuableField - 表格列

如何进行totalCountOfValuableFIeld字段?

totalCountOfValuableField - 不是表中的列,而是每个id-token对的不同`valuableField的总数。

我尝试了这个查询,但它强迫我对行进行分组,但这不是我想要的。

select id, token, valuableField, count(distinct valuableField) from table_1

示例数据

当前表

╔════════╦═════════════╦═══════════════╗
║ id     ║ token       ║ valuableField ║ 
╠════════╬═════════════╬═══════════════╣
║     88 ║ test        ║ unique1       ║
║     88 ║ test        ║ duplicate1    ║
║     88 ║ random1     ║ 1unique       ║
║     88 ║ test        ║ duplicate1    ║
║     76 ║ bar         ║ 1unique       ║
║     76 ║ bar         ║ 2unique       ║
╚════════╩═════════════╩═══════════════╝

我想要什么

╔════════╦═════════════╦═══════════════╦════════════════════════════╗
║ id     ║ token       ║ valuableField ║ totalCountOfValuableField  ║ 
╠════════╬═════════════╬═══════════════╬════════════════════════════╣
║     88 ║ test        ║ unique1       ║            2               ║
║     88 ║ test        ║ duplicate1    ║            2               ║
║     88 ║ random1     ║ 1unique       ║            1               ║
║     88 ║ test        ║ duplicate1    ║            2               ║
║     76 ║ bar         ║ 2unique       ║            2               ║
║     76 ║ bar         ║ 3unique       ║            2               ║
╚════════╩═════════════╩═══════════════╩════════════════════════════╝

2 个答案:

答案 0 :(得分:2)

不幸的是,Postgres(尚未)支持window function中的distinct。根据{{​​3}},您可以执行以下操作:

select id, 
       token, 
       valuableField, 
       count(*) filter (where rn = 1) over (partition by id, token) 
from (
  select id, token, valuableField, 
         row_number() over (partition by id, token, valuableField) as rn
  from table_1
) t

答案 1 :(得分:1)

根据您的预期结果,您似乎希望根据valuableFieldid计算不同的token你用COUNT DISTINCT OVER执行此操作:

select
  id,
  token,
  valuableField,
  count(distinct valuableField) over (partition by id, token) as total
from mytable;

<击>

UPDATE:如前所述,PostgreSQL在窗口函数中不支持DISTINCT。所以你必须使用子查询:

select
  id,
  token,
  valuableField,
  (
    select count(distinct m2.valuableField)
    from mytable m2
    where m2.id = m1.id and m2.token = m1.token
  ) as total 
from mytable m1;

然而,这不是“id-token对如何有一个有价值的领域”。如果您需要,则必须按valuableField进行分区,并计算不同的id / token对。