繁体   English   中英

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

[英]Select distinct rows by first column and max of second

我有下表:

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分组的所有表,仅采用max 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问题中添加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.

您的查询应该像这样;

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

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

您应该在下面的查询中尝试此操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM