输入表格:销售数据
+---------------+---------------+---------- +-----------+
| Child | Parent | Level | Sales |
+---------------+---------------+---------- +-----------+
| All Region | All Region | 1 | 1000000 |
| Africa Region | All Region | 2 | 159816 |
| America | All Region | 2 | 114054 |
| Asia | All Region | 2 | 74028 |
| Europe Region | All Region | 2 | 116766 |
| Africa | Africa Region | 3 | 81954 |
| Asia Pacific | Asia | 3 | 144306 |
| Europe | Europe Region | 3 | 1440 |
| North America | America | 3 | 8185 |
| South America | America | 3 | 8440 |
| Argentina | South America | 4 | 470 |
| Australia | Asia Pacific | 4 | 9040 |
| Pakistan | Asia Pacific | 4 | 705 |
| South Africa | Africa | 4 | 45 |
| Tunisia | Africa | 4 | 385 |
| Uruguay | South America | 4 | 420 |
+-------------------------------------------------------+
等级
我需要输出记录,其中有两列,一个是CHILD,另一列是MAX_Sale
,在MAX_Sale
列中,相应子数据的兄弟之间只有最大销售额。
示例:
+-----------+------------+
| Childs | Max_sales |
+-----------+------------+
| Austrlia | 9040 |
| Pakistan | 9040 |
| S.Africa | 385 |
| Tunisia | 385 |
+------------------------+
由于澳大利亚和巴基斯坦都属于同一父母而澳大利亚拥有最大销售额
答案 0 :(得分:4)
您可以使用窗口函数(row_number
)来获得此结果:
select child, MAX_Sale
from (
select child,
sales as MAX_Sale,
row_number() over (partition by parent order by sales desc) as rn
from t
) sub
where rn = 1
...假设您的表名为 t 。根据需要更换。
输出是:
Child | MAX_Sale
---------------+---------
Tunisia | 385
Africa | 81954
All Region | 1000000
South America | 8440
Asia Pacific | 144306
Australia | 9040
Europe | 1440
Argentina | 470
根据您的需要,您可能仍需要按级别进行过滤,并应用特定的排序顺序。
但是,如果你需要列出所有地区,以及销售最好的兄弟姐妹,那么:
select child,
first_value(sales) over (partition by parent order by sales desc) as MAX_Sale
from t
输出:
Child | MAX_Sale
--------------+----------
Tunisia | 385
South Africa | 385
Africa | 81954
All Region | 1000000
Africa Region | 1000000
Europe Region | 1000000
America | 1000000
Asia | 1000000
South America | 8440
North America | 8440
Asia Pacific | 144306
Australia | 9040
Pakistan | 9040
Europe | 1440
Argentina | 470
Uruguay | 470
first_value
是"analytic function",用于“窗口函数”的上下文中:over
clause定义了一个窗口函数来应用窗口函数。
答案 1 :(得分:1)
如果我理解正确,您需要一个类似于此的查询:
SELECT
Child,
MAx_Sales
FROM table1 inner join
(
SELECT
Parent,
max(Sales) as Max_sales
FROM table1
GROUP BY Parent
) as table2
on table1.Parent = table2.Parent
答案 2 :(得分:1)
我认为以下代码适合您:
Select child, Sales as Max_Sales
from table A
where Sales >= All (Select Sales from table B
Where A.level=B.Level
and A.Parent=B.Parent)
这是根据以下理解 比如说,SubRegion A作为4个子国家p,q,r,s然后我们需要在最大销售额的四个国家中名称和销售。