我正在尝试按子类聚合(计算)数据,但是我需要根据整体类别计数按降序排序吗?
例如,我的列标题是:
tbl (table name)
singularity_id (key)
product_cat (category)
consumption_location (sub-category)
我的SQL查询是:
SELECT
product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
tbl
GROUP BY
product_cat, consumption_location
ORDER BY
product_cat, consumption_location, count DESC;
这对product_cat和consumption_location进行分组,但不按product_cat count desc。
排序所以基于我的查询,我的数据目前看起来像这样:
product_cat | consumption_location | count
------------+----------------------+--------
Fruit Juice | Store | 200
Fruit Juice | Home | 600
Soft Drink | Store | 1200
Soft Drink | Home | 100
Water | Store | 400
Water | Home | 500
我想要的是:
product_cat | consumption_location | count
------------+----------------------+--------
Soft Drink | Store | 1200
Soft Drink | Home | 100
Water | Store | 400
Water | Home | 500
Fruit Juice | Store | 200
Fruit Juice | Home | 600
由于软饮料的总体条目最多,其次是水,然后是果汁。
答案 0 :(得分:0)
with temptbl as
(select distinct product_cat, consumption_location,
count(SINGULARITY_ID) over (partition by product_cat) cntcat ,
count(SINGULARITY_ID) over (partition by
product_cat,consumption_location) as cntsub
from t2 order by cntcat desc
)
select product_cat ,consumption_location , cntsub from temptbl ;
答案 1 :(得分:0)
如果没有临时表,您可以为分区添加一个"总计"
SELECT
product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count,
count(*) over (partition by product_cat) as total
FROM
tbl
GROUP BY
product_cat, consumption_location
ORDER BY
total Desc, product_cat, consumption_location
但你可以完全从select语句中省略总数并按顺序添加它,因为它是一个聚合
SELECT
product_cat, consumption_location, COUNT(DISTINCT singularity_id) as count
FROM
tbl
GROUP BY
product_cat, consumption_location
ORDER BY
count(*) over (partition by product_cat) Desc, consumption_location
虽然我不确定为什么你总是把商店放在最顶层,但这样可以让你得到你所需的样品。所以我只是通过这两个其他字段来订购其他字段在你的例子中似乎只有最后的总数然后在整体总数之后,consumption_location似乎在提升