我有这行代码
select min(A.id) 'id',
CONVERT (VARCHAR(10),min(A.date_in),101) as 'Date_in',
CONVERT (VARCHAR(10),min(A.date_in),108) as 'Time_in',
CONVERT (VARCHAR(10),min(A.date_out),101) as 'Date_out',
CONVERT (VARCHAR(10),min(A.date_out),108) as 'Time_out',
min(B.firstname) 'firstname',min(B.lastname) 'lastname',
min(A.ip_address) 'ip_address',
CASE min(B.UserType)
WHEN 1029 THEN 'Administator'
WHEN 1030 THEN 'Casheiring'
WHEN 1031 THEN 'Front Office'
WHEN 1032 THEN 'Housekeeping'
WHEN 1033 THEN 'POS'
END as 'user_type'
from AEmployeeLogs A
LEFT JOIN AUsers B on B.id = A.[user_id]
group by A.[user_id]
ORDER BY min(A.id) DESC
在这个查询中,我得到了这个:
id Date_in Time_In Date Out Time_Out firstname lastname ip_address user_type
5 10/05/2017 15:14:59 10/05/2017 20:20:37 LeBron James 192.168.0.1 Administrator
1 10/04/2017 12:04:32 10/05/2017 16:02:53 Kevin Durant 192.168.0.2 Administrator
这些将为我提供我分组的2个ID我想要在每个日期都应该在那里每次我希望它像这样:
id Date_in Time_In Date Out Time_Out firstname lastname ip_address user_type
5 10/05/2017 15:14:59 10/05/2017 20:20:37 LeBron James 192.168.0.1 Administrator
3 10/05/2017 11:58:20 10/05/2017 16:02:53 Kevin Durant 192.168.0.2 Administrator
1 10/04/2017 12:04:32 10/05/2017 16:02:53 Kevin Durant 192.168.0.2 Administrator
它应该有这个输出我只想在每个日期得到min()而不是整个表的min(),即使是group by子句请帮帮我,谢谢:)
答案 0 :(得分:1)
我想你想要这样的东西。
select *
from
(
select A.id,
CONVERT (VARCHAR(10), A.date_in,101) as 'Date_in',
CONVERT (VARCHAR(10), A.date_in,108) as 'Time_in',
CONVERT (VARCHAR(10), A.date_out,101) as 'Date_out',
CONVERT (VARCHAR(10), A.date_out,108) as 'Time_out',
B.firstname,
B.lastname,
A.ip_address,
CASE B.UserType
WHEN 1029 THEN 'Administator'
WHEN 1030 THEN 'Casheiring'
WHEN 1031 THEN 'Front Office'
WHEN 1032 THEN 'Housekeeping'
WHEN 1033 THEN 'POS'
END as 'user_type'
, RowNum = ROW_NUMBER() over(partition by A.id, A.date_in order by A.date_in)
from AEmployeeLogs A
LEFT JOIN AUsers B on B.id = A.[user_id]
) x
where x.RowNum = 1
ORDER BY x.id DESC
此外,您应该使用比A
,B
,C
等更好的别名。这是一个不好的习惯。