按第一列和第二列的最大值选择不同的行

时间:2019-03-20 08:40:52

标签: sql tsql group-by distinct

我有下表:

Item           Prod        Company
1.00961.501    PR011798    ditto
1.00961.501    PR012042    ditto
1.00961.501    PR013442    Pika
1.00961.502    PR012043    ditto
1.00961.503    PR011959    ditto
1.00961.503    PR011669    Bulb
1.00961.507    PR014783    ditto
1.00961.507    PR012050    ditto

我想选择按Item分组的所有表,仅使用最大Prod。像这样:

Item           Prod        Company
1.00961.501    PR012042    ditto
1.00961.502    PR012043    ditto
1.00961.503    PR011959    ditto
1.00961.507    PR014783    ditto

我尝试了以下操作:

SELECT  DISTINCT Item, MAX(Prod)
FROM    DataBase
WHERE   Company = 'ditto'

但这给了我

Column 'Item' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

如果我删除了MAX条款,则不会返回任何错误,但是Item对每个Prod都会重复。

有什么想法吗?

编辑

我忘了在问题中添加Where子句。 当我这样做时,尝试使用Group By而不是Distinct时出现以下错误:

Column 'Company' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

2 个答案:

答案 0 :(得分:1)

您的查询应该是这样;

SELECT  Item, MAX(Prod),Company
FROM    DataBase
WHERE   Company = 'ditto'
GROUP BY Item,Company;

答案 1 :(得分:0)

您需要对产品进行分区,然后从该分区中选择一个。

您应该在下面的查询中尝试使用此方法。

  select Item, Prod, Company from 
  (
    select *,
    (ROW_NUMBER() over (partition by Item order by Prod DESC)) as Row from [table_name] 
    where Company = 'ditto'
  ) t where Row = 1