2014-08-29 127 views
0

我试图通过site.Site_Name,为每个hive.hiveno和它的最大值(hiverdg.invdate)。运行下面的代码不起作用,因为site.Site_Name没有被聚集。如果我添加site.Site_Name对GROUP BY,代码运行,但输出中显示结果重复,每进行一次site.Site_Name按SQL中的多列分组

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 
+0

您希望看到哪个网​​站?与'max(invdate)'关联的那个? – Vland 2014-08-29 10:14:38

+0

Vland - 是的,这是正确的 – user1936588 2014-08-29 10:17:11

+0

hiveno组,通过选择hiveno和max(invdate)。然后使用子查询/连接来获取site_name,其中日期等于max(invdate) – Vland 2014-08-29 10:21:08

回答

0

要做到这一点,最简单的方式,与您的查询,是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,简化了逻辑。