Select 第一列不同的行和第二列的最大值
Select distinct rows by first column and max of second
我有以下 table:
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
我想 select 所有 table 按 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
子句,它 returns 没有错误,但是 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.
您的查询应该是这样的;
SELECT Item, MAX(Prod),Company
FROM DataBase
WHERE Company = 'ditto'
GROUP BY Item,Company;
您需要对产品进行分区,然后 select 从该分区中提取一个。
您应该尝试下面的查询。
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
我有以下 table:
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
我想 select 所有 table 按 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
子句,它 returns 没有错误,但是 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.
您的查询应该是这样的;
SELECT Item, MAX(Prod),Company
FROM DataBase
WHERE Company = 'ditto'
GROUP BY Item,Company;
您需要对产品进行分区,然后 select 从该分区中提取一个。
您应该尝试下面的查询。
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