如何在 select 语句中找到最频繁的值作为子查询?

How to find the most frequent value in a select statement as a subquery?

我正在尝试从 table B 获取最频繁的 Zip_Code 位置 ID。Table A(交易)每个交易有一个 A.zip_code,但是 table B(Location) 在一个地区或城市有多个 Zip_code。我正在尝试使用 table.I 中存在的 Location_D 为帐户获取最频繁的 B.Zip_Code 简化了我的代码并更改了列的名称以便于理解,但这是我的查询逻辑我有 far.Any 帮助将不胜感激。提前致谢。

Select
           A.Account_Number,
           A.Utility_Type,
           A.Sum(usage),
           A.Sum(Cost),
           A.Zip_Code,
           ( select B.zip_Code from B where A.Location_ID= B.Location_ID  having count(*)= max(count(B.Zip_Code)) as Location_Zip_Code,
            A.Transaction_Date


From 
            Transaction_Table as A Left Join
            Location Table as B  On A.Location_ID= B.Location_ID


Group By   
              A.Account_Number,
              A.Utility_Type,
              A.Zip_Code,
              A.Transaction_Date

这是我想出的:

Select tt.Account_Number, tt.Utility_Type, Sum(tt.usage), Sum(tt.Cost),
       tt.Zip_Code,
       (select TOP 1 l.zip_Code
        Location_Table l
        where tt.Location_ID = l.Location_ID 
        group by l.zip_code
        order by count(*) desc
       ) as Location_Zip_Code,
       tt.Transaction_Date
From Transaction_Table tt 
Group By tt.Account_Number, tt.Utility_Type, tt.Zip_Code, tt.Transaction_Date;

备注:

  • Table 别名是个好东西。但是,它们应该是引用的 table 的缩写,而不是任意字母。
  • table 别名限定列名,而不是函数。因此 sum(tt.usage) 而不是 tt.sum(usage).
  • 外部查询不需要连接。您正在执行子查询中的所有工作。
  • order bytop 似乎是获取最常见邮政编码的方法(顺便说一下,这在统计中称为模式)。