我写了一个查询,显示了每个州每年取消订单的原因和所选原因的数量:
SELECT DISTINCT LEFT(k.wijk,2) AS state,
YEAR(a.eind_dt) AS year,
opzegreden AS reason,
count(*) AS amount
FROM klant AS k
JOIN abon AS a
ON k.klant_id = a.lezer
WHERE opzegreden IS NOT NULL
GROUP BY LEFT(k.wijk,2), year(a.eind_dt), opzegreden
ORDER BY state, year, reason;
这给出了这个结果atm: Current result
现在我唯一无法实现的目的是显示每年每州最多的原因。我目前的结果是14号的原因。
有人可以帮帮我吗?
答案 0 :(得分:1)
您可以将top with ties
与窗口函数row_number
配对,以获得每年每州最大金额的行。
select top 1 with ties LEFT(k.wijk, 2) as state,
YEAR(a.eind_dt) as year,
opzegreden as reason,
count(*) as amount
from klant as k
join abon as a on k.klant_id = a.lezer
where opzegreden is not null
group by LEFT(k.wijk, 2),
year(a.eind_dt),
opzegreden
order by row_number() over (
partition by state, year order by amount desc
);
答案 1 :(得分:0)
你可以试试这个: -
SELECT
state,
year,
reason,
max(amount)
FROM
(
SELECT DISTINCT LEFT(k.wijk,2) AS state,
YEAR(a.eind_dt) AS year,
opzegreden AS reason, count(*) AS amount
FROM klant AS k
JOIN abon AS a
ON k.klant_id = a.lezer
WHERE opzegreden IS NOT NULL
GROUP BY LEFT(k.wijk,2), year(a.eind_dt), opzegreden
ORDER BY state, year, reason
) d
GROUP BY
state,
year,
reason;