坚持什么是简单的查询

时间:2011-01-16 15:59:41

标签: sql sql-server

如果我有2张桌子用于人,一张用于假期。每当有人去度假时,日期都会输入到假期表中。我如何查询这一点,如果他们在2010年1月1日至2010年6月6日之间的2个假期,那么它会显示人员表中的人名?这似乎很简单,但我似乎无法做到。

4 个答案:

答案 0 :(得分:2)

SELECT people.name, COUNT(*) c
FROM people INNER JOIN holidays
ON people.user_id = holidays.user_id
WHERE holidays.departure_date BETWEEN date1 AND date2
GROUP BY people.name
HAVING c > 2

答案 1 :(得分:2)

如果您想要的是在这两个日期之间需要2天或更长时间的人员名单:

SELECT people.name
FROM people
WHERE EXISTS (
  SELECT count(*)
  FROM days_taken
  WHERE people.person_id=days_taken.person_id AND
  days_taken.vacation_date BETWEEN date1 AND date2
  HAVING count(*)>=2
)

如果您想要名称​​和天数:

SELECT people.name,count(*)
FROM people JOIN days_taken ON people.person_id=days_taken.person_id
WHERE days_taken.vacation_date BETWEEN date1 AND date2
GROUP BY people.name
HAVING count(*)>=2

答案 2 :(得分:0)

SELECT p1.name, p2.num_holidays
FROM people p1
INNER JOIN 
(
SELECT people.user_id, COUNT(*) as num_holidays
FROM people 
INNER JOIN holidays  ON (people.user_id = holidays.user_id)
WHERE holidays.departure_date BETWEEN date1 AND date2
GROUP BY people.user_id
HAVING  COUNT(*) > 2
)p2 ON (p2.user_id = p1.user_id)

答案 3 :(得分:0)

对于SQL Server 2005以上版本,您可以使用分析函数Count()OVER

select p.*, h.C
from person p inner join
(
    select distinct person_id, C = COUNT(*) over (partition by person_id)
    from holiday
    where holiday_date between '20100101' and '20100606'
) h on h.person_id = p.person_id and h.C >= 2