如何使用PSQL窗口函数计算相同类别和不同类别的出现次数?

时间:2019-03-17 03:37:37

标签: psql window-functions

(
SELECT
  foods.id,
  foods.category,
  ??? OVER (PARTITION BY foods.category) as same_category_order_of_occurance,
  ??? OVER (PARTITION BY foods.category) as different_category_order_of_occurance
FROM foods
) as condition ON conditions.id = foods.id
```

To product this result.

```
id | category  | same_category_order_of_occurance  | different_category_order_of_occurance
---+-----------+-----------------------------------+---------------------------------------
1  |FRUIT      | 1                                 | 1                  
2  |FRUIT      | 2                                 | 1
3  |VEG        | 1                                 | 2
4  |VEG        | 2                                 | 2
5  |MEAT       | 1                                 | 3
6  |MEAT       | 2                                 | 3
```

Uncertain what functions to use which help me produce this ordering.

0 个答案:

没有答案