简体   繁体   English

如何简化“MAX”运算符的 SQL 代码

[英]How to simplify SQL code for "MAX" operator

I was trying to solve one task and found the solution, it works, but the code is "awful" and duplicates itself, may be someone can just help me with that?我试图解决一项任务并找到了解决方案,它有效,但代码“糟糕透了”并且自我复制,可能有人可以帮我解决这个问题?

SELECT  b."N",b."ID",max(b.summ) as "jjj", b.country

FROM(SELECT großhandelsfirma.name as "N",großhandelsfirma.steuerid as "ID",
sum(verkauft.anzahl) as "summ", großhandelsfirma.land as "country"
FROM großhandelsfirma
INNER JOIN verkauft on großhandelsfirma.name = verkauft.ghname
GROUP BY großhandelsfirma.name,großhandelsfirma.steuerid,großhandelsfirma.land) b
WHERE b.summ in (SELECT  max(b.summ)

FROM(SELECT großhandelsfirma.name as "N",großhandelsfirma.steuerid as "ID",
sum(verkauft.anzahl) as "summ", großhandelsfirma.land as "country"
FROM großhandelsfirma
INNER JOIN verkauft on großhandelsfirma.name = verkauft.ghname
GROUP BY großhandelsfirma.name,großhandelsfirma.steuerid,großhandelsfirma.land) b
GROUP BY b.country)
GROUP BY b."N",b."ID", b.country

Original code was ok, but gave me solution with not needed lines, the main task was to find company with highest "sum" in each country, but I got some duplicates with countries, so answer included 2-3 best "summs" in 1 country, but I needed only 1.原始代码没问题,但给了我不需要行的解决方案,主要任务是找到每个国家/地区“总和”最高的公司,但我与国家/地区有一些重复,因此答案包括 1 中的 2-3 个最佳“总和”国家,但我只需要 1。

This was the old code:这是旧代码:

SELECT großhandelsfirma.name as N, großhandelsfirma.steuerid as ID,
sum verkauft.anzahl as summ, großhandelsfirm.land as country
FROM großhandelsfirma
INNER JOIN verkauft on großhandelsfirma.name = verkauft.ghname
GROUP BY großhandelsfirma.name, großhandelsfirma.steuerid, großhandelsfirma.land

Perhaps the window function ROW_NUMBER has been implemented in your RDBMS.也许您的 RDBMS 中已经实现了窗口函数 ROW_NUMBER。
It can be used to calculate a number based on an order.它可用于根据订单计算数字。
So it'll be 1 for the top 1.所以前1名将是1。

SELECT N, ID, country, summ
FROM
(
  SELECT f.name as N, f.steuerid as ID, f.land as country
  , SUM(v.anzahl) as summ
  , ROW_NUMBER() OVER (PARTITION BY f.land ORDER BY SUM(v.anzahl) DESC) as RN
  FROM großhandelsfirma f
  JOIN verkauft v ON f.name = v.ghname
  GROUP BY f.name, f.steuerid, f.land
) q
WHERE RN = 1

Did you try doing the same with CTE?你有没有尝试用 CTE 做同样的事情? Please have a look into below link.请查看以下链接。

CTE CTE

Or else use the TOP 1 from the result filtered.或者使用过滤结果中的 TOP 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM