sql - 对子查询/表返回的每一行执行选择并组合(联合)结果

标签 sql amazon-redshift

我想对子查询/表返回的集合的每一行执行选择语句。然后我想合并结果并将其视为一个集合。

我有一个表 tbl1 -

city|zip|contractor|budget
==========================
LA  |010| A        | 100
LA  |010| A        | 200
LA  |010| B        | 50
LA  |010| D        | 25
LA  |020| A        | 400
LA  |020| C        | 200
LA  |020| C        | 350

我正在执行的第一条语句是 -

select group,city,sum(budget) from tbl1 group by city,zip

这会产生一个像这样的表格(tbl2)-

city|zip||budget
==========================
LA  |010|375
LA  |020|950

然后,我想在此表上运行查询来对排名前 2 的承包商进行排名。所以我希望对 tbl2 中的每一行运行以下语句,然后合并(联合)结果 -

    select TOP 2 contractor,sum(budget) as budget_sum from tbl1 where city = <city_value_for_row> and zip = <zip_value_for_row> 
group by contractor order by budget_sum desc

我最终想要的表格是这样的:

    city|zip|contractor|budget_sum
    ==========================
    LA  |010| A        | 300
    LA  |010| B        | 50  
    LA  |020| C        | 550
    LA  |020| A        | 400

^^通过对 tbl2 上的第 1 行执行选择而得到的前两行。 后两行是对 tbl2 中的第 2 行执行选择的结果。

换句话说,我希望能够根据一组城市和邮政编码对承包商进行排名,并且我希望对城市和邮政编码的每种可能的组合执行此操作。

有没有一套基于方法来做到这一点?或者我是否必须迭代 tbl2 中的每一行,执行 select,插入临时表,然后获取结果?

最佳答案

您需要加入 2 个查询:

select t.city, t.zip, t.contractor, t.tsum
from (
  select 
    t.city, t.zip, t.contractor, g.budget_sum gsum, t.budget_sum tsum,
    row_number() over (partition by t.city, t.zip order by g.budget_sum, t.budget_sum desc) rn  
  from (
    select city, zip, contractor, sum(budget) budget_sum
    from tbl1 
    group by city, zip, contractor
  )  t inner join (
    select city, zip, sum(budget) budget_sum
    from tbl1 
    group by city, zip  
  ) g 
  on g.city = t.city and g.zip = t.zip
) t
where t.rn <= 2
order by t.gsum, t.tsum desc

请参阅demo .
结果:

| city | zip | contractor | budget_sum |
| ---- | --- | ---------- | ---------- |
| LA   | 10  | A          | 300        |
| LA   | 10  | B          | 50         |
| LA   | 20  | C          | 550        |
| LA   | 20  | A          | 400        |

关于sql - 对子查询/表返回的每一行执行选择并组合(联合)结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57420989/

相关文章:

sql - Oracle 实体属性值 (EAV) 数据库表中带有 WHERE 子句的 LEFT JOIN 列

MySQL UNION - 每个派生表都必须有自己的别名

sql - 包含 INSERT 语句的 WHERE 子句、WHERE 处的 "Incorrect Syntax"以及 IF NOT EXISTS 运行,无论记录是否存在

amazon-web-services - 将 PySpark 连接到 AWS Redshift 时出错

sql - 相当于TEXT数据类型的redshift

amazon-web-services - AWS Redshift 中的并发查询、复制和连接

sql - 如果可用,请在该月加入,否则请在最近一个月加入

javascript - toLocaleDateString() 是减去一天

amazon-redshift - AWS Glue:如何使用各种模式处理嵌套JSON

sql - SQL Server 2012 中的旧 SSIS