查询在ID相同时获取所有数据

时间:2017-01-16 11:25:38

标签: sql tsql

我有一张桌子可以返回这些结果。

ProcessID   AddressID   ItemStateID
22             2            50
22             3            50
22             4            50
22             5            50
22             6            50
22             7            60
22             7            50
22             8            50
22             9            50
22             10           60
22             10           50
22             11           50
22             12           50

但我想要的是:

ProcessID   AddressID   ItemStateID
22             2            50
22             3            50
22             4            50
22             5            50
22             6            50
22             7            60
22             8            50
22             9            50
22             10           60
22             11           50
22             12           50

当AddressID相同时,我希望在一行中获得最高的ItemStateID ......

现在这是我正在使用的查询:

SELECT DISTINCT
    ProcessID,
    AddressID,
    ItemStateID
FROM MMResult2
WHERE ProcessID = 22 AND ItemStateID > 10
ORDER BY AddressID ASC, ItemStateID DESC

4 个答案:

答案 0 :(得分:2)

删除distinct并按您想要唯一的列分组。要汇总最后一列,请使用max()

SELECT ProcessID,
       AddressID,
       max(ItemStateID) as MaxItemStateID
FROM MMResult2
WHERE ProcessID = 22 
  AND ItemStateID > 10
GROUP BY ProcessID,
         AddressID
ORDER BY AddressID ASC, 
         max(ItemStateID) DESC

答案 1 :(得分:0)

您可以使用GROUP BY

SELECT 
    ProcessID,
    AddressID,
    MAX(ItemStateID)
FROM MMResult2
WHERE ProcessID = 22 AND ItemStateID > 10
GROUP BY AddressID

答案 2 :(得分:0)

使用GROUP BYMAX功能。

SELECT DISTINCT ProcessID, AddressID, MAX(ItemStateID) AS HighestItemStateID
FROM MMResult2
WHERE ProcessID = 22 AND ItemStateID > 10
GROUP BY ProcessID, AddressID, 
ORDER BY AddressID ASC, ItemStateID DESC

答案 3 :(得分:0)

SELECT 
    ProcessID,
    AddressID,
    MAX(ItemStateID)  AS ItemStateID 
FROM MMResult2
WHERE ProcessID = 22 AND ItemStateID > 10
GROUP BY ProcessID, AddressID
ORDER BY AddressID ASC, ItemStateID DESC