【问题标题】:Grouping by multiple columns in SQLSQL中按多列分组
【发布时间】:2014-08-29 10:09:24
【问题描述】:

我正在尝试为每个 hive.hiveno 引入 site.Site_Name,它是 max(hiverdg.invdate)。运行下面的代码不起作用,因为 site.Site_Name 没有聚合。如果我将 site.Site_Name 添加到 Group By,代码会运行,但输出会显示重复的结果,每个 site.Site_Name 一次

select site.Site_Name ,hive.hiveno, max(hiverdg.invdate)
from hiverdg 
        inner join hive
        on        hiveRdg.hive_Link = hive.hive_Link
        inner join Customer
        on        customer.Customer_Link = hive.Customer_Link
        inner join site
        on        site.Customer_Link = customer.Customer_Link        
where 
(hiverdg.xtype = 'N'
and customer.CustomerName = 'Cust1')
or
(hiverdg.xtype = 'A'
and customer.CustomerName = 'Cust1')
group by hive.hiveno

【问题讨论】:

  • 您想看哪个网站?与max(invdate) 关联的那个?
  • Vland - 是的,没错
  • 按 hiveno 分组,像你一样选择 hiveno 和 max(invdate)。然后使用子查询/连接来获取日期等于 max(invdate) 的 site_name
  • 你需要的可能和这个解决方案类似:stackoverflow.com/questions/612231/…

标签: mysql sql max distinct


【解决方案1】:

使用您的查询最简单的方法是 substring_index()/group_concat() 技巧:

select substring_index(group_concat(s.Site_Name order by rdg.invdate desc separator '|'
                                   ), '|', 1
                      ) as SiteName,
       h.hiveno, max(rdg.invdate)
from hiverdg rdg inner join
     hive h
     on rdg.hive_Link = h.hive_Link inner join
     Customer c
     on c.Customer_Link = h.Customer_Link inner join
     site s
     on s.Customer_Link = c.Customer_Link        
where rdg.xtype in ('N', 'A') and c.CustomerName = 'Cust1')
group by h.hiveno;

我还对您的查询进行了以下更改:

  • 引入了表别名,使查询更易于编写和阅读。
  • where 改为使用in,简化了逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    相关资源
    最近更新 更多