我有报告表,每天汇总每个产品数量的数据。
SELECT r.year, r.month, c.id, c.client_name, p.product_name, cc.country_name, sum(r.quantity) units FROM
client c
join report r on c.id = r.client_id
join product p on r.product_id = p.id
join country cc on r.country_id = c.id
WHERE r.year = year(now())
group by r.year, r.month, c.id, p.product_name, cc.country_name
我正在试图弄清楚群组单位按月,客户,产品和国家的总和,其中查询显示前5个国家的总和,其余是来自底层国家的总和。像这样:
case
when sum(r.quantity) = 'Top 1' then cc.country_name
when sum(r.quantity) = Top 2' then cc.country_name
.....
when sum(r.quantity) = 'Top 2' then cc.country_name
else 'Other'
我该怎么做?
非常感谢提前
答案 0 :(得分:0)
你可以试试这个。在这里,我将结果从大多数数量减少到更少,并添加行号。所以前6名是最高的。
请尝试,但我无法测试。
SELECT
@nr := ( @nr +1) AS nr,
IF ( @nr < 7, CONCAT('Top ',@nr), 'other' ) AS top,
r.* FROM (
SELECT r.year, r.month, c.id, c.client_name, p.product_name, cc.country_name, sum(r.quantity) units
FROM CLIENT c
JOIN report r ON c.id = r.client_id
JOIN product p ON r.product_id = p.id
JOIN country cc ON r.country_id = c.id
WHERE r.year = YEAR(now())
GROUP BY r.year, r.month, c.id, p.product_name, cc.country_name
ORDER BY sum(r.quantity) DESC
) AS r
CROSS JOIN ( SELECT @nr:=0 ) AS params;