简体   繁体   中英

Select records based on one distinct column

I am new to SQL. I am using SQL Server.

I am writing a query to get top scores (sc) of each user (unique).

I have written a query which results in a table having non-unique values of pname and pid.

I have the following resultant table

 id     pid pname   sc
___________________________

1584    268 user1   99
1608    268 user1   99
1756    268 user1   95
1750    268 user1   95
1240    268 user1   94
1272    268 user1   94
1290    268 user1   93
1298    268 user1   93
1177    268 user1   93
1488    268 user1   93
1401    268 user1   92
1407    268 user1   92
1482    268 user1   89
1245    268 user1   89
1705    268 user1   88
2848    310 user2   81
2888    310 user2   81
1178    268 user1   80
2084    50  user3   80
2727    50  user3   80
2729    50  user3   80
2782    50  user3   80
2792    50  user3   79
2848    50  user3   79
2851    310 user2   79
2833    310 user2   78
2851    50  user3   78
2857    50  user3   78
2619    50  user3   77
2890    50  user3   77
2593    310 user2   77
2596    310 user2   77
2792    310 user2   77
2810    310 user2   77
2806    310 user2   76

from this query

SELECT
    t.id,
    t.pid,
    u.pname,
    t.sc
FROM
    table t,
    table u
WHERE
    t.pid=u.pid
GROUP BY
    id,
    pid,
    u.pname
ORDER BY
    sc DESC

What i want is to have unique pnames in my resultant table. For example the required output should be:

id     pid pname   sc
___________________________

1584    268 user1   99
2851    310 user2   79
2084    50  user3   80

ie first maximum 'sc' of each user

Thank you!

The typical approach to this problem is not GROUP BY but window functions. These are ANSI standard functions that include ROW_NUMBER() :

SELECT id, pid, pname, sc
FROM (SELECT t.id, t.pid, u.pname, t.sc,
             ROW_NUMBER() OVER (PARTITION BY u.pid ORDER BY t.sc DESC) as seqnum
      FROM table t JOIN
           table u
           ON t.pid = u.pid
     ) tu
WHERE seqnum = 1;

You can try this:

select id,pid,pname,sc 
from
(
   select t.id,t.pid,u.pname,t.sc,
          DENSE_RANK() over (partition by pname order by sc desc) as rank 
     from t,u where t.pid=t.pid=u.pid  
) x 
where x.rank=1;

as I have just created one table based on your given records after running i am getting following output.

select id,pid,pname,sc from
(
    select id,pid,pname,sc,
    DENSE_RANK() over (partition by pname order by sc desc) as rank 
    from t 
) x 
where x.rank=1;

Query result:

在此处输入图片说明

You can use a simple SQL query like this:

SELECT t.ID, t.pid, u.pname, t.sc
FROM table1 t,
     table2 u
WHERE t.pid = u.pid
    AND t.sc = (
        SELECT MAX(d.sc)
        FROM table1 d
        WHERE t.pname = d.pname
    )
ORDER BY sc DESC

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