简体   繁体   中英

SQL Server : query grouping

I have some queries in SQL Server. I have two tables

  1. keyword_text

  2. Keyword_relate

Columns in keyword_text :

  1. key_id
  2. keywords

Columns in keyword_relate :

  1. key_id
  2. product_id
  3. score
  4. status

Sample data for keyword_text :

----|----------
1   | Pencil
2   | Pen
3   | Books

Sample data for keyword_relate :

----------------------------
Sno| Product | SCore|status
---------------------------
1  | 124     | 2    | 1
1  | 125     | 3    | 1
2  | 124     | 3    | 1
2  | 125     | 2    | 1    

From this I want to get the product_id , grouped by keywords and which have maximum score

Presuming that key_id of first table is Sno in second table. You can use ROW_NUMBER :

WITH CTE AS
(
    SELECT Product AS ProductID, Score As MaxScore,
           RN = ROW_NUMBER() OVER (PARTITION BY kt.key_id ORDER BY Score DESC)
    FROM  keyword_text kt INNER JOIN keyword_relate kr
    ON kt.key_id = kr.Sno
)
SELECT ProductID, MaxScore
FROM CTE
WHERE RN = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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