SQL服务器 - 分组依据和替换

时间:2017-06-24 05:56:58

标签: sql sql-server

我有一张桌子

+--------+-----+
| Gender | AGE |
+--------+-----+
| M      |  10 |
| F      |  29 |
| M      |  30 |
| F      |  40 |
| F      |   5 |
+--------+-----+

我希望有一个输出,其中显示每个性别最旧的输出,并添加一个列,表明它们是最早的。什么查询即将使用?

示例输出:

+--------+-----+--------+
| Gender | Age |  Tag   |
+--------+-----+--------+
| M      |  30 | Oldest |
| F      |  40 | oldest |
+--------+-----+--------+

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

只是一个简单的Group by

DECLARE @SampleData AS TABLE
(
    Gender varchar(1),
    Age int
)

INSERT INTO @SampleData
(
    Gender,
    Age
)
VALUES
( 'M', 10),
( 'F', 29),
( 'M', 30),
( 'F', 40),
( 'F', 5 )

SELECT  sd.Gender, 
        max(sd.Age) AS Age,
        'Oldest' AS [Tag]
FROM @SampleData sd
GROUP BY sd.Gender

返回

Gender  Age Tag
-----------------
F       40  Oldest
M       30  Oldest