-1

我有这个数据集:

|  ID | TYPE | PERCENT |
------|------|---------|
| 123 |    A |     0.5 |
| 123 |    B |     0.5 |
| 456 |    A |     0.7 |
| 456 |    B |     0.3 |
| 789 |    A |       1 |

我想要以下结果:

|  ID | TYPE | PERCENT |
------|------|---------|
| 123 |    A |     0.5 |
| 456 |    A |     0.7 |
| 789 |    A |       1 |

也就是说,获取MAX(percent)for eachid和对应的type.

我目前正在使用

SELECT ... 
FROM
  (SELECT [id], MAX([percent]) AS [p]
  FROM [highest]
  GROUP BY [id]) a
LEFT JOIN [highest] b 
  ON b.[id] = a.[id]
    AND b.[percent] = a.[p]

并得到

|  ID |   P | TYPE | PERCENT |
--- --|-----|------|---------|
| 123 | 0.5 |    A |     0.5 |
| 123 | 0.5 |    B |     0.5 |
| 456 | 0.7 |    A |     0.7 |
| 789 |   1 |    A |       1 |
4

2 回答 2

3

试试这个查询:

SELECT  src.[id], src.[type], src.[percent]
FROM (
    SELECT  [id], [type], [percent], 
            ROW_NUMBER() OVER(PARTITION BY h.[id] ORDER BY [percent] DESC, h.[type] ASC) AS RowNum
    FROM    [highest] h
) src
WHERE src.RowNum = 1
于 2013-09-23T18:48:13.657 回答
1

另一种给猫剥皮的方法:

SELECT d.ID, m.type, m.[percent]
FROM highest AS d
CROSS APPLY (
  SELECT TOP 1 type, [percent]
  FROM highest
  WHERE ID = d.ID
  ORDER BY [percent] DESC, type ASC
) AS m
GROUP BY d.ID, m.type, m.[percent]
;

也就是说,对于每个 distinct ID,获取具有最大值 ( TOP 1 ... ORDER BY [percent] DESC)的行percent。当多个类型具有相同 ID 的最大值时,type ASC选择排在其他 ( ) 之前的类型。

稍微不那么冗长的等价物(使用 DISTINCT 而不是 GROUP BY):

SELECT DISTINCT d.ID, m.type, m.[percent]
FROM highest AS d
CROSS APPLY (
  SELECT TOP 1 type, [percent]
  FROM highest
  WHERE ID = d.ID
  ORDER BY [percent] DESC, type ASC
) AS m
;

有了适当的索引,应该不会比@Bogdan Sahlean 的建议差多少。

于 2013-09-24T06:20:31.473 回答