问题
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