You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跨表对比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 JOIN only returns matching pairs. Use FULL OUTER JOIN to include unmatched rows (you’ll need to handle NULL ratings for those cases).
  • Adjust Names: Replace TableA, TableB, Shows, and Rating with your actual table and column names.

内容的提问来源于stack exchange,提问作者tadm123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:06:05