SQL:合并 table 并将每个单元格除以另一个 table 中的匹配单元格?

SQL: Joining tables and dividing each cell by match cell in another table?

这是我的人口数据集,详细说明了 2010 年至 2019 年每个州的人口:

这是我的消费者投诉数据集,其中包含收到日期和状态:

我已经有每个州每年的投诉:

我知道我需要在州内加入 compltsbypear 和 uspop,并将 2011 年(来自投诉)/2011 年与 uspop 等划分为每个比赛年。

如何编写显示各州和每年投诉与人口比率的查询?

我会通过逆透视人口数据来解决这个问题,因此每个州和年份都有一行。然后汇总投诉和join.

您的代码看起来像 SQL 服务器,所以我将使用这些约定:

with up as (
      select v.*
      from uspop u cross apply
           (values (u.area, 2010, u.[2010]),
                   (u.area, 2011, u.[2011]),
                   . . . 
          ) v(state, year, pop)
     ),
     cc as (
      select year(datereceived) as year, state, count(*) as num_complaints
      from consumercomplaints cc
      group by year(datereceived), state
     )
select up.state, up.year, cc.num_complaints, up.pop,
       (cc.num_complaints * 1.0 / up.pop) as complaint_ratio
from up join
     cc
     on up.state = cc.state and up.year = cc.year;

这会以每 state/year 一行的完全合理的格式生成您想要的结果。如果你想要不同的格式,你似乎知道如何旋转数据。