时间:2016-03-09 07:06:49

标签: sql-server tsql

以下是我实际失败的实际面试问题。只是好奇什么是正确的答案。

鉴于以下表格:

SELECT * FROM users;

user_id  username
1        John Doe                                                                                            
2        Jane Don                                                                                            
3        Alice Jones                                                                                         
4        Lisa Romero

SELECT * FROM training_details;

user_training_id  user_id  training_id  training_date
1                 1        1            "2015-08-02"
2                 2        1            "2015-08-03"
3                 3        2            "2015-08-02"
4                 4        2            "2015-08-04"
5                 2        2            "2015-08-03"
6                 1        1            "2015-08-02"
7                 3        2            "2015-08-04"
8                 4        3            "2015-08-03"
9                 1        4            "2015-08-03"
10                3        1            "2015-08-02"
11                4        2            "2015-08-04"
12                3        2            "2015-08-02"
13                1        1            "2015-08-02"
14                4        3            "2015-08-03"

撰写查询以获取在同一天多次参加培训课程的用户列表,按用户和培训课程分组,每个用户从最近的课程日期到最早的日期进行排序。

4 个答案:

答案 0 :(得分:3)

除非我遗漏了什么,否则应该是这样的:

SELECT username, tranning_date
FROM users u
INNER JOIN training_details t ON(u.user_id = t.user_id)
GROUP BY username, tranning_date
HAVING COUNT(*) > 1
ORDER BY username, tranning_date DESC

答案 1 :(得分:1)

Select
   u.user_id,
   username,
   training_id,
   training_date,
   count (user_training_id) AS count
From users u JOIN training_details t ON t.user_id= u.user_id
Group By user_id, 
         username, 
         training_id,
         training_date
Having count(user_training_ id) > 1
Order By training_date DESC;

答案 2 :(得分:0)

`SELECT u.USERNAME, t.USER_ID, t.TRAINING_DATE, COUNT(t.TRAINING_ID) 
 FROM training_details t JOIN USERS u ON (u.id = t.user_id)
 GROUP BY u.USERNAME,t.USER_ID, t.TRAINING_ID, t.TRAINING_DATE
 HAVING COUNT(t.TRAINING_ID)>1
 ORDER BY t.TRAINING_DATE DESC;`


Results => 

"USERNAME",     "USER_ID","TRAINING_DATE","COUNT(T.TRAINING_ID)"
"Lisa Romero",   4,         08-04-2015,        2
"Lisa Romero",   4,         08-03-2015,        2
"John Doe",      1,         08-02-2015,        3
"Alice Jones",   3,         08-02-2015,        2

答案 3 :(得分:0)

SELECT username, training_date ,  count(*) as count
FROM users u
INNER JOIN training_details t ON(u.user_id = t.user_id)
GROUP BY username, training_date
having count(*) > 1
ORDER BY username,training_date DESC