我有一张名为PayGrade的表,我的记录很少。我想显示不同的数据,但要根据具体的列
IF EXISTS(SELECT 1 FROM sys.tables WHERE object_id = OBJECT_ID('PayGrade'))
BEGIN;
DROP TABLE [PayGrade];
END;
GO
CREATE TABLE [PayGrade] (
[PayGradeID] INTEGER NOT NULL IDENTITY(1, 1),
[ChangeDate] VARCHAR(255),
[PayGrade] VARCHAR(255) NULL,
[Pay] INTEGER NULL,
PRIMARY KEY ([PayGradeID])
);
GO
INSERT INTO PayGrade([ChangeDate],[PayGrade],[Pay]) VALUES('2017-07-22 13:38:26','Grade 12','10000');
INSERT INTO PayGrade([ChangeDate],[PayGrade],[Pay]) VALUES('2018-01-31 02:33:02','Grade 12','10000');
INSERT INTO PayGrade([ChangeDate],[PayGrade],[Pay]) VALUES('2018-01-31 18:30:36','Grade 14','15000');
通过此查询,我得到了相应的输出。
SELECT DISTINCT ChangeDate, PayGrade, Pay
FROM PayGrade
输出:
Change Date PayGrade Pay
2017-07-22 13:38:26 Grade 12 10000
2018-01-31 02:33:02 Grade 12 10000
2018-01-31 18:30:36 Grade 14 15000
期望的输出:
Change Date PayGrade Pay
2017-07-22 13:38:26 Grade 12 10000
2018-01-31 18:30:36 Grade 14 15000
答案 0 :(得分:2)
您可以使用Group By
和Min
功能执行此操作 -
SELECT MIN(ChangeDate) as ChangeDate, PayGrade, Pay
FROM PayGrade
GROUP BY PayGrade, Pay
答案 1 :(得分:1)
您的预期输出似乎意味着您希望,对于一组给定的薪资等级和薪水,您需要第一个/最早的记录。如果是这样,那么我们可以使用行号如下:
SELECT
[Change Date],
PayGrade,
Pay
FROM
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY PayGrade, Pay ORDER BY [Change Date]) rn
FROM PayGrade
) t
WHERE rn = 1;