Sql server 选择键相同但某个属性最低的行
我有下表Sql server 选择键相同但某个属性最低的行,sql-server,Sql Server,我有下表 Key Year_month Ammount 1 201612 100 1 201701 120 2 201605 1000 2 201608 800 3 201705 500 我只需要使用最低的年/月值为每个键选择一行 e、 g:这应该是查询的结果 Key Year_month Ammount 1 201612
Key Year_month Ammount
1 201612 100
1 201701 120
2 201605 1000
2 201608 800
3 201705 500
我只需要使用最低的年/月值为每个键选择一行
e、 g:这应该是查询的结果
Key Year_month Ammount
1 201612 100
2 201605 1000
3 201705 500
问题是我真的不知道该怎么做,我试着用
SELECT
KEY,
YEAR_MONTH,
AMMOUNT
FROM TABLE AS T1
WHERE YEAR_MONTH =(SELECT TOP 1 YEAR_MONTH FROM TABLE WHERE KEY = T1.KEY)
但这不起作用另一种方法
declare @table table ([key] int, year_month int, amount int)
insert into @table ([key], year_month, amount)
values (1, 201612, 100),
(1, 201701, 120),
(2, 201605, 1000),
(2, 201608, 800),
(3, 201705, 500)
select t.*,
(select t2.amount from @table t2 where t2.[key] = t.[key] and t2.year_month = t.year_month) as amount
from ( select [key], min(year_month) as year_month
from @table
group by [key]
) t
这是回报
key year_month amount
--- ---------- ------
1 201612 100
2 201605 1000
3 201705 500
试试这个
DECLARE @T TABLE
(
[Key] INT,
Year_month VARCHAR(10),
Amount FLOAT
)
INSERT INTO @T
VALUES('1','201612','100'),
('1','201701','120'),
('2','201605','1000'),
('2','201608','800'),
('3','201705','500')
;WITH CTE
AS
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY [Key] ORDER BY CAST(Year_month+'01' AS DATE) ASC),
*
FROM @T
)
SELECT
[Key],
Year_month,
Amount
FROM CTE
WHERE RN = 1
Select DT.* FROM Data_Table DT
JOIN
( SELECT [KEY], Min(Year_month) AS MinYM FROM Data_Table GROUP BY [KEY] ) DX
ON DX.[KEY]= DT.[KEY] AND DX.MinYM = DT.Year_month ;
DROP TABLE IF EXISTS #tmp_test01
CREATE TABLE #tmp_test01 ( [KEY] INT
, Year_Month INT
, Amount INT
)
INSERT INTO #tmp_test01
VALUES
(1, 201612, 100)
, (1, 201701, 120)
, (2, 201605, 1000)
, (2, 201608, 800)
, (3, 201705, 500)
WITH CTE AS (
SELECT ROW_NUMBER() OVER (PARTITION BY [KEY] ORDER BY [KEY], [Year_Month]) RN
, [KEY]
, Year_Month
, Amount
FROM #tmp_test01
)
SELECT [KEY]
, Year_Month
, Amount
FROM CTE
WHERE RN = 1