简体   繁体   English

如何找到最低值和相应的日期SQL-Server 2014

[英]How to find the lowest value and the corresponding date SQL-Server 2014

I have the sample data See the SQL Fiddle . 我有示例数据, 请参见SQL Fiddle I want to find the lowest value from the value column and the date of lowest value from the uploaded-date column. 我想从值列中找到最低值,并从上载日期列中找到最低值的日期。 I tried the following query and it is not properly working and showing all values. 我尝试了以下查询,但它无法正常工作并显示所有值。

SELECT
    username,
    MIN(Value1) AS MinValue1,
    CASE 
        WHEN value1 = MIN(value1) THEN uploaded_date
    END
    AS MinDate
FROM
    test

GROUP BY
    username

You could use the RANK window function to find the minimal value for each username: 您可以使用RANK窗口函数来找到每个用户名的最小值:

SELECT username, value1, uploaded_date
FROM   (SELECT username, value1, uploaded_date,
               RANK() OVER (PARTITION BY username ORDER BY value1 ASC) AS rk
        FROM   test) t
WHERE  rk = 1

SQLFIddle SQLFIddle

SELECT test. username,value1,MIN(uploaded_date  )FROM
(Select MIN(value1) MinValue1,username from test group by username ) A
INNER JOIN
test 
ON A.MinValue1 = test.Value1
AND A.username = test.username
GROUP BY
test. username,value1

Your query did not work because you were using the columns in the select list so the Group by clause will group all distinct values into each row 您的查询无效,因为您正在使用选择列表中的列,因此Group by子句会将所有不同的值分组到每一行中

i hope this will help you 我希望这能帮到您

  ;with CTE as(
    SELECT username,
      MIN(Value1) AS MinValue1
  FROM
      test
  GROUP BY 
    username
  )

  select c.username,MinValue1,dt.uploaded_date from CTE c
  cross apply(select top 1 uploaded_date from test where value1=c.MinValue1 and username=c.username order by uploaded_date desc) dt
select Value1, update_date from test order by Value1 limit 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM