我遇到一个问题,需要在一天内显示每个组,用户,状态,某个字段的最大值。
groupno user status date amount
74 user1 status_1 2016-01-01 05:40:00.0 900
74 user1 status_1 2016-01-01 05:45:00.0 1200
79 user1 status_2 2016-01-01 05:45:31.0 31
79 user1 status_2 2016-01-01 05:50:00.0 300
79 user1 status_2 2016-01-01 05:55:00.0 600
79 user1 status_2 2016-01-01 06:00:00.0 900
79 user1 status_2 2016-01-01 06:05:00.0 1200
90 user1 status_1 2016-01-01 06:07:52.0 172
90 user1 status_1 2016-01-01 06:10:00.0 300
90 user1 status_1 2016-01-01 06:15:00.0 600
我正在尝试使用内部联接来最大化每个组的最大数量,但是因为我再次检索所有值而无法正常工作:
select t.groupno, t.user, t.status, t.date, t.amount
from ( select groupno,user, status, date, max (amount) as maxact from table group by 1,2,3,4) as m
Inner
join table as t
on t.user= m.user
and t.amount= m.maxact
and t.status = m.status
and t.date = m.date
答案 0 :(得分:1)
使用窗口功能:
select t.*,
max(t.amount) over (partition by groupno, user, status, date_trunc('day', date)) as max_amount
from t;
我认为groupno
/ user
/ status
/天是计算最大值的维度。
答案 1 :(得分:0)
如果你只想要最大金额,就日期而言 - 你可以拿MAX并将日期时间作为日期:
DECLARE @temp TABLE (groupno int, [user] varchar(20), status varchar(20), date datetime, amount int)
INSERT INTO @temp
VALUES
(74,'user1', 'status_1', '2016-01-01 05:40:00.0', 900)
,(74,'user1', 'status_1', '2016-01-01 05:45:00.0', 1200)
,(79,'user1', 'status_2', '2016-01-01 05:45:31.0', 31)
,(79,'user1', 'status_2', '2016-01-01 05:50:00.0', 300)
,(79,'user1', 'status_2', '2016-01-01 05:55:00.0', 600)
,(79,'user1', 'status_2', '2016-01-01 06:00:00.0', 900)
,(79,'user1', 'status_2', '2016-01-01 06:05:00.0', 1200)
,(90,'user1', 'status_1', '2016-01-01 06:07:52.0', 172)
,(90,'user1', 'status_1', '2016-01-01 06:10:00.0', 300)
,(90,'user1', 'status_1', '2016-01-01 06:15:00.0', 600)
SELECT groupno, [user], [status], CAST([date] as date) [Date], MAX(amount) as MAXamount
FROM @temp
GROUP BY groupno, [user], [status], CAST([date] as date)
答案 2 :(得分:0)
不确定我是否完全按照这个问题查看,但是我希望你想要每组最大数量的行。为此,您可以尝试:
SELECT t.groupno, t.user, t.status, t.date, t.amount
FROM t
INNER JOIN
(SELECT groupno, MAX(amount) as mx
FROM t
GROUP BY groupno) sub
ON t.groupno = sub.groupno
WHERE t.amount = sub.mx