0

我有两张桌子

用户表

 user_id | name  |
    1    | peter |
    2    | kofi  |
    3    | sam   |
    4    | nasah |
    5    | sarah |
    6    | david |

时间表

 time_id | user_id | register
    1    |     1   |  present
    2    |     2   |  absent
    3    |     3   |  absent
    4    |     3   |  absent
    5    |     4   |  present
    6    |     5   |  absent
    7    |     5   |  absent

我怎样才能找到少于 2 个寄存器的名称。请帮我处理 SQL 中的这段代码

4

1 回答 1

1

你只需使用group byhaving

select users.user_id, users.name, count(times.time_id) registers
  from users 
       left outer join times 
                    on times.user_id = users.user_id
 group by users.user_id, users.name
 having count(*) < 2;

例如:

SQL> with users as (select 1 user_id, 'Peter' name from dual union all
  2                 select 2 user_id, 'kofi' name from dual union all
  3                 select 3 user_id, 'sam' name from dual union all
  4                 select 4 user_id, 'nasah' name from dual union all
  5                 select 5 user_id, 'sarah' name from dual union all
  6                 select 6 user_id, 'david' name from dual),
  7  times as (select 1 time_id, 1 user_id, 'present' register from dual union all
  8            select 2 time_id, 2 user_id, 'absent' register from dual union all
  9            select 3 time_id, 3 user_id, 'absent' register from dual union all
 10            select 4 time_id, 3 user_id, 'absent' register from dual union all
 11            select 5 time_id, 4 user_id, 'present' register from dual union all
 12            select 6 time_id, 5 user_id, 'absent' register from dual union all
 13            select 7 time_id, 5 user_id, 'absent' register from dual)
 14  select users.user_id, users.name, count(times.time_id) registers
 15    from users
 16         left outer join times
 17                      on times.user_id = users.user_id
 18   group by users.user_id, users.name
 19   having count(*) < 2;

   USER_ID NAME   REGISTERS
---------- ----- ----------
         6 david          0
         1 Peter          1
         4 nasah          1
         2 kofi           1
于 2013-01-31T11:32:39.037 回答