SQL:Display distinct ids for all the set of values from table

随声附和 提交于 2019-12-11 16:23:49

问题


I have a problem where after executing a query i'm getting a result like this

DevID   Difference      
-----------------
99       5        
99       10   
99       5        
99       4 
12       8        
12       9 
12       5        
12       6 

i dont want the duplicate ids, I should be able to display only one id. This could be easily achieved by using distinct however the problem is i also need to display the Difference column. I'm not bothered which value comes in diff but either one of the values for 99 can come there but basically i just need one value for id. Expected result is something like this.

DevID   Difference      
-----------------
99       5        
12       8  

If it helps this question is continuation of the following question Difference of values that belong to same group but stored in two rows


回答1:


You can use GROUP BY along with MAX or MIN or any other aggregation function to get a result as you expected.

SELECT DevID, MAX(Difference) 
FROM Yourtablename
GROUP BY DevID



回答2:


use aggregation function max().

select DevID, max(Difference) 
from tableA
group by DevID



回答3:


Please try this example you need to change this query in your actual query.

NOTE: As per your expected output for I'm prepared for example.

DECLARE @Table TABLE
(
    DevID   INT,
    [Difference]     INT
);

INSERT INTO @Table VALUES
(99,5),(99,10 ),(99,5),(99,4),(12,8),(12,9),(12,5),(12,6)

--SELECT * FROM @Table
SELECT * FROM
(
    SELECT DevID,[Difference],
    ROW_NUMBER() OVER(PARTITION BY DevID  ORDER BY DevID) AS RN 
    FROM @Table 
) AS Data
WHERE RN=1
ORDER BY [Difference]

Output



来源:https://stackoverflow.com/questions/59170935/sqldisplay-distinct-ids-for-all-the-set-of-values-from-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!