简体   繁体   English

SQL - Select 与多列和条件不同

[英]SQL - Select Distinct with multiple columns and conditions

I have a set of data as shown below, how to return results with distinct Set, course_id, exercise_id and test_mode, with the condition of longest testing_name.我有一组数据如下图,如何返回不同Set、course_id、executive_id和test_mode的结果,条件是最长testing_name。 Many thanks.非常感谢。

Set course_id course_id exercise_id运动编号 test_mode测试模式 testing_name测试名称 testing_count testing_count
A一个 5 5 4 4 C C test(12)测试(12) 2 2
A一个 5 5 4 4 C C test(12) and test(34)测试(12)和测试(34) 3 3
A一个 5 5 4 4 P test(22)测试(22) 2 2
A一个 5 5 4 4 B B 5 5
A一个 3 3 20 20 C C test(49)测试(49) 1 1
A一个 3 3 15 15 B B 5 5
B 5 5 4 4 B B 3 3
B 5 5 4 4 P test(33) and test(87)测试(33)和测试(87) 3 3
B 5 5 4 4 P test(88)测试(88) 1 1

Expected results:预期成绩:

Set course_id course_id exercise_id运动编号 test_mode测试模式 testing_name测试名称 testing_count testing_count
A一个 5 5 4 4 C C test(12) and test(34)测试(12)和测试(34) 3 3
A一个 5 5 4 4 P test(22)测试(22) 2 2
A一个 5 5 4 4 B B 5 5
A一个 3 3 20 20 C C test(49)测试(49) 1 1
A一个 3 3 15 15 B B 5 5
B 5 5 4 4 B B 3 3
B 5 5 4 4 P test(33) and test(87)测试(33)和测试(87) 3 3

Use ROW_NUMBER here:在此处使用ROW_NUMBER

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Set, course_id, exercise_id, test_mode
                                 ORDER BY LENGTH(testing_name) DESC) rn
                                 -- use LEN() for SQL Server
    FROM yourTable
)

SELECT Set, course_id, exercise_id, test_mode, testing_name, testing_count
FROM cte
WHERE rn = 1;

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

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