我有一个查询,它在一个月的每天中获取最大值。我想做的就是获取结果的时间,而不仅仅是日期。
SELECT convert(date,a.time) AS monthly, MAX(a.Va) AS monthlyVA, MAX(a.vb) AS monthlyVB
FROM tbl_sample a
WHERE DATEPART(month, a.time) = 10 and DATEPART(year, a.time) = 2018
GROUP by convert(date,a.time)
我得到的结果:
我得到的结果是正确的,但我还想查看时间,而不仅是每月列中的日期。列时间的数据类型已经是日期时间。如果仅选择时间,则结果如下。我要获取的只是显示日期和时间的每月每个月的最大数据。
SELECT a.time AS monthly, MAX(a.Va) AS monthlyVA, MAX(a.vb) AS monthlyVB
FROM tbl_sample a
WHERE DATEPART(month, a.time) = 10 and DATEPART(year, a.time) = 2018
GROUP by time
答案 0 :(得分:0)
使用row_number()
窗口功能。 partition by
dateadd(day, datediff(day, 0, a.time), 0)
将按天为您提供电话号码。在这里,我假设您想要基于Va
的最大值,后跟Vb
SELECT *
FROM
(
SELECT *,
rn = row_number() over (partition by dateadd(day, datediff(day, 0, a.time), 0)
order by a.Va desc, a.Vb desc)
FROM tbl_sample a
WHERE DATEPART(month, a.time) = 10 and DATEPART(year, a.time) = 2018
) d
WHERE d.rn = 1
答案 1 :(得分:0)
您可以尝试使用相关子查询
SELECT a.time AS monthly, a.Va AS monthlyVA, a.vb AS monthlyVB
FROM tbl_sample a
WHERE DATEPART(month, a.time) = 10 and DATEPART(year, a.time) = 2018
and exists
(select 1 from tbl_sample b where convert(date,a.time)=convert(date,b.time)
group by GROUP by convert(date,a.time) having max(b.Va)=a.Va and max(b.Vb)=a.Vb
)
答案 2 :(得分:-1)
您只需在查询中使用CONVERT(datetime,a.time)
代替CONVERT(date,a.time)
。
如果您的要求有所不同,那么您可以发送一些示例数据,现在我不太清楚。