如何通过组少列比选择(How to group by less columns than selec

2019-10-18 10:47发布

我在这里面临的一个问题(使用SQL Server 2005)。

我的SELECT查询如下所示:

SELECT 
a.str_column1, b.str_column2, c.date_column3, c.guid_column4
FROM table
....
joining the other tables here to get my columns
....
GROUP BY 
    a.str_column1, b.str_column2, c.date_column3, c.guid_column4

这将给像这样

a.str_column1    b.str_column2    c.date_column3    c.guid_column4
------------------------------------------------------------------
a1               b1                15/07/2013       someID    
a2               b2                05/06/2012       someID
a1               b1                07/08/2013       someID
....

现在我想,这样它是由分组a.str_column1b.str_column2 ,只得到最近的一次( order by c.dat_column3

a.str_column1    b.str_column2    c.date_column3    c.guid_column4
------------------------------------------------------------------
a1               b1                07/08/2013       someID
a2               b2                05/06/2012       someID

任何想法我如何与SQL做到这一点?

Answer 1:

您可以使用ROW_NUMBER()并能够消除GROUP BY完全:

SELECT
    *
FROM (
  SELECT 
  a.str_column1, b.str_column2, c.date_column3, c.guid_column4,
  ROW_NUMBER() OVER (PARTITION BY a.str_column1, b.str_column2
                     ORDER BY c.date_column3 DESC) as rn
  FROM table
  ....
  joining the other tables here to get my columns
  ....
  --No longer needed GROUP BY a.str_column1, b.str_column2, c.date_column3, c.guid_column4
) t
WHERE t.rn = 1

为了能够在结果查询ROW_NUMBER()函数,你必须把你的现有查询(用在新列SELECT列表)为子查询(如上)或公用表表达式。



Answer 2:

您sholud使用max功能date_column3柱和group by子句如下删除列

SELECT 
a.str_column1, b.str_column2, max(c.date_column3) as column3, c.guid_column4
FROM table
....
joining the other tables here to get my columns
....
GROUP BY a.str_column1, b.str_column2,c.guid_column4


文章来源: How to group by less columns than selected