跨表对比Shows列关联Rating值,输出对应较大值的技术需求
Solution for Comparing Shows and Their Ratings Across Two Tables
To solve this problem—matching shows by their occurrence order (even when names repeat) and identifying which table has the higher associated rating—follow these steps using SQL:
Step 1: Assign Row Numbers to Handle Duplicate Shows
First, add a row number to each table, partitioned by the Shows column. This ensures duplicate shows are paired in their original order (1st occurrence with 1st, 2nd with 2nd, etc.).
Step 2: Join Tables and Compare Ratings
Join the two ranked tables on both the Shows name and the row number, then compare the ratings to determine which is higher.
Full Query Example
Assume your tables are named TableA and TableB, each containing Shows and Rating columns:
WITH RankedTableA AS ( SELECT Shows, Rating, -- Assign row number within each Show group to preserve order ROW_NUMBER() OVER (PARTITION BY Shows ORDER BY (SELECT NULL)) AS occurrence_num FROM TableA ), RankedTableB AS ( SELECT Shows, Rating, ROW_NUMBER() OVER (PARTITION BY Shows ORDER BY (SELECT NULL)) AS occurrence_num FROM TableB ) SELECT rtA.Shows, rtA.occurrence_num, -- Determine which table has the higher rating CASE WHEN rtA.Rating > rtB.Rating THEN 'TableA' WHEN rtB.Rating > rtA.Rating THEN 'TableB' ELSE 'Ratings are equal' END AS higher_rating_source, -- Get the highest rating value between the pair GREATEST(rtA.Rating, rtB.Rating) AS highest_rating FROM RankedTableA rtA INNER JOIN RankedTableB rtB ON rtA.Shows = rtB.Shows AND rtA.occurrence_num = rtB.occurrence_num;
Key Notes:
- Preserving Original Order: The
ORDER BY (SELECT NULL)clause retains the original row order for duplicate shows. If your tables have a specific column defining order (like an ID or timestamp), replace(SELECT NULL)with that column for more reliable ordering. - Handling Mismatched Occurrences: If one table has more instances of a show than the other,
INNER JOINonly returns matching pairs. UseFULL OUTER JOINto include unmatched rows (you’ll need to handleNULLratings for those cases). - Adjust Names: Replace
TableA,TableB,Shows, andRatingwith your actual table and column names.
内容的提问来源于stack exchange,提问作者tadm123
相关产品推荐
相关产品推荐

