2017-04-06 104 views
1

Retreiving數據我有一個結果/表,該表如下使用SQL查詢特定場景

user_id |date_time |name | ---------|------------------|------| 1 |05/04/2017 08:00 |Jack | 2 |05/04/2017 09:00 |Adams | 1 |05/04/2017 13:06 |Jack | 1 |05/04/2017 13:45 |Jack | 1 |06/04/2017 09:15 |Jack | 1 |07/04/2017 10:00 |Jack | 1 |10/04/2017 12:00 |Jack | 2 |10/04/2017 12:30 |Adams | 1 |10/04/2017 15:44 |Jack |

我想升序排序date_time針對每個用戶的每一天。 我期待的結果如下:(我有第二行和最後一個問題)。 JackApril 5的所有行應該在一起,接着是Adams;的Adamsdate_time是否在Jackdate_time之間的那一天

user_id |date_time |name | ---------|------------------|------| 1 |05/04/2017 08:00 |Jack | 1 |05/04/2017 13:06 |Jack | 1 |05/04/2017 13:45 |Jack | 2 |05/04/2017 09:00 |Adams | 1 |06/04/2017 09:15 |Jack | 1 |07/04/2017 10:00 |Jack | 1 |10/04/2017 12:00 |Jack | 1 |10/04/2017 15:44 |Jack | 2 |10/04/2017 12:30 |Adams |


添加我已經習慣在此ResultSet到達查詢:

SELECT DISTINCT user_table.user_id 
    ,diary_table.date_time 
    ,user_table.NAME 
FROM user_table 
INNER JOIN diary_table ON user_table.user_id = diary_table.diary_user_id 
    AND (
     date_time >= '06-Apr-2017 00:00:00' 
     AND date_time <= '15-Apr-2017 23:59:59' 
     ) 
    AND diar_user_id IN (
     SELECT DISTINCT diar_user_id 
     FROM diary_table 
     INNER JOIN event_table ON event_table.event_id = diary_table.diar_event_id 
     WHERE event_table.event_name = 'Lunch' 
      AND (
       date_time >= '06-Apr-2017 00:00:00' 
       AND date_time <= '15-Apr-2017 23:59:59' 
       ) 
     ) 
ORDER BY date_time ASC 
    ,NAME 
    ,ASC 
+0

你到目前爲止嘗試過什麼?包括那個以及 –

+0

好吧,這是一個SQL查詢的結果,我堅持這個結果集。 – Reema

+0

你可以發佈我們查詢你使用? –

回答

0

得到這個要解決使用一天的專欄。這裏是查詢:

SELECT DISTINCT DISTINCT DATEADD(DAY, DATEDIFF(DAY, 0, date_time), 0) AS theDay 
    ,user_table.user_id 
    ,diary_table.date_time 
    ,user_table.NAME 
FROM user_table 
INNER JOIN diary_table ON user_table.user_id = diary_table.diary_user_id 
    AND (
     date_time >= '06-Apr-2017 00:00:00' 
     AND date_time <= '15-Apr-2017 23:59:59' 
     ) 
    AND diar_user_id IN (
     SELECT DISTINCT diar_user_id 
     FROM diary_table 
     INNER JOIN event_table ON event_table.event_id = diary_table.diar_event_id 
     WHERE event_table.event_name = 'Lunch' 
      AND (
       date_time >= '06-Apr-2017 00:00:00' 
       AND date_time <= '15-Apr-2017 23:59:59' 
       ) 
     ) 
ORDER BY theDay 
    ,NAME ASC 
    ,date_time ASC