计算不同的和窗口函数

时间:2016-06-21 20:58:57

标签: sql distinct window-functions

我有一个ID列表,交易,这些交易的日期以及这些交易的类别。我想在每个ID中创建每个不同类别的计数

我的起始表看起来像这样:

id  trxn_dt     trxn_amt trxn_category
1   10/31/2014  58       apple
1   11/9/2014   34       banana
1   12/10/2014  12       apple
2   7/8/2014    78       banana
2   11/20/2014  99       banana
3   1/5/2014    120      orange
4   2/17/2014   588      apple
4   2/18/2014   8        banana
4   3/9/2014    65       orange
4   4/25/2014   74       apple

我希望最终结果看起来像这样:

id  trxn_dt     trxn_amt trxn_category  number_category
1   10/31/2014  58       apple          2
1   11/9/2014   34       banana         2 
1   12/10/2014  12       apple          2
2   7/8/2014    78       banana         1
2   11/20/2014  99       banana         1
3   1/5/2014    120      orange         1
4   2/17/2014   588      apple          3
4   2/18/2014   8        banana         3
4   3/9/2014    65       orange         3
4   4/25/2014   74       apple          3

我已尝试使用count(distinct(trxn_category)) over(partition by id,trxn_category order by id) as number_category但我收到有关使用' distinct'

的错误

3 个答案:

答案 0 :(得分:1)

大多数DBMS不支持窗口函数中的DISTINCT,但您可以使用两个DENSE_RANK来模拟COUNT(DISTINCT):

DENSE_RANK() over (partition by id,trxn_category order by id ASC)-
DENSE_RANK() over (partition by id,trxn_category order by id DESC)

或嵌套MAX(DENSE_RANK):

select
   MAX(dr) over (partition by id,trxn_category)
from
 (
   select 
      DENSE_RANK() over (partition by id,trxn_category order by id DESC) as dr
 ) 

答案 1 :(得分:0)

您可以使用相关的子查询:


<field-exclude type="one-way""> 
  <a>createdDate</a> 
  <b>createdDate</b> 
</field-exclude>

Demo here

答案 2 :(得分:0)

SELECT id, trxn_dt, trxn_amt, trxn_category,
       (SELECT COUNT(DISTINCT trxn_category)
        FROM mytable AS t2
        WHERE t2.id = t1.id) AS cnt
FROM mytable AS t1

无法在分区聚合中使用DISTINCT。