简体   繁体   English

DB2 SQL 根据权重选择不同的数据

[英]DB2 SQL Select Distinct Data Based On Weighting

I have a table of categories, each of which has a weighting applied to it.我有一个类别表,每个类别都有一个权重。

I have a table of Products and Categories that they appear in, and want to select the Category with the highest weighting for each Product.我有一个产品和类别表,它们出现在其中,并希望为每个产品选择权重最高的类别。

I have tried to use Distinct, but it doesn't seem to want to work with sort.我曾尝试使用 Distinct,但它似乎不想使用 sort。

My basic query would be:我的基本查询是:

select a.product, a.category from prodcattable a
join categorytable b on a.category=b.category
order by product, weighting desc

Where a product appears in multiple categories, I just want to return one row, with the product and the category that ranks the highest.当一个产品出现在多个类别中时,我只想返回一行,其中包含排名最高的产品和类别。

This needs to work in DB2 as I need to run it on an iSeries.这需要在 DB2 中工作,因为我需要在 iSeries 上运行它。

I am hoping that I can use the result to compare against a master product table to see if the category has changed, without having to read through the whole master product table, and for each product find the category with the highest weighting.我希望我可以使用结果与主产品表进行比较,以查看类别是否已更改,而无需通读整个主产品表,并为每个产品找到权重最高的类别。 With over 75,000 products, that's a lot of queries to execute.拥有超过 75,000 种产品,需要执行大量查询。

One method uses row_number() :一种方法使用row_number()

select pc.*
from (select p.product, p.category,
             row_number() over (partition by p.product order by weighting desc) as seqnum
      from prodcattable p join
           categorytable c
           on p.category= c.category
     ) pc
where seqnum = 1;

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

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