我有示例数据See the SQL Fiddle。我想从上载日期列中找到值列中的最小值和最低值的日期。我尝试了以下查询,但它没有正常工作并显示所有值。
SELECT
username,
MIN(Value1) AS MinValue1,
CASE
WHEN value1 = MIN(value1) THEN uploaded_date
END
AS MinDate
FROM
test
GROUP BY
username
答案 0 :(得分:1)
您可以使用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 强>
答案 1 :(得分:1)
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
您的查询无效,因为您使用的是选择列表中的列,因此Group by子句会将所有不同的值分组到每一行
答案 2 :(得分:0)
我希望这会对你有所帮助
;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
答案 3 :(得分:-1)
select Value1, update_date from test order by Value1 limit 1