选择子查询中具有最小值的其他列

时间:2016-10-26 08:04:50

标签: sql-server

有没有办法选择子查询中具有MIN值的其他列? 在我的子查询中,我生成了值列表。那么如何获得我产生该值的时间

这是我的代码:

Select A, (select Time from result where value = ??MIN VALUE), MIN (value)
from (
      //subquery
     ) result
group by A 

我的子查询产生的数据示例:

A              Time                       Value
ABC     2016-10-26 15:00:00.000             10
ABC     2016-10-26 15:00:01.000             5
ABC     2016-10-26 15:00:02.000             15
DEF     2016-10-26 15:00:05.000             20
DEF     2016-10-26 15:00:06.000             25

预期结果:

A              Time                       Value
ABC     2016-10-26 15:00:01.000             5
DEF     2016-10-26 15:00:05.000             20

3 个答案:

答案 0 :(得分:1)

select top 1 with ties a,time,value
from
table
order by row_number() over (partition by a order by value)

答案 1 :(得分:1)

使用ROW_NUMBER()

SELECT s.a,s.time,s.value
FROM(
    SELECT t.*,
           ROW_NUMBER() OVER(PARTITION BY t.a ORDER BY t.time) as rnk
    FROM YourTable t) s
WHERE s.rnk = 1

如果可以联系,请将ROW_NUMBER()替换为RANK()

答案 2 :(得分:0)

使用RANK():

DECLARE @tblTest AS TABLE(
    A VARCHAR(5),
    Value INT
)

INSERT INTO @tblTest VALUES
('ABC',10),
('ABC',5),
('ABC',15),
('DEF',20),
('DEF',25),
('GHI',20),
('GHI',7),
('GHI',7)

;WITH T AS
(
    SELECT
        *,
        RANK() OVER(Partition By A ORDER BY Value) AS PartNo
    FROM @tblTest
)
SELECT 
    *
FROM T
WHERE T.PartNo=1

<强>输出:

enter image description here