SQL 查询一个人在每个生命年中工作了多少小时

SQL query to find how many hours a person has worked in each life year

我有两个table

Person(id, birthdate)

Workday(personid, date, hours)

birthdatedate 都采用 YYYYMMDD 格式,存储为字符串。

我需要一个 returns table 的查询,其中包含一个人的年龄 (0, 1, 2...) 以及该人在这一年中工作了多少小时 (一年将包括该人的生日月份)。

这是我目前拥有的:

SELECT CONVERT(INT, SUBSTRING(w.date, 0, 7)) - CONVERT(INT, SUBSTRING(p.birthdate, 0, 7)) AS age, w.hours AS totalhours
FROM Person AS p INNER JOIN Workday AS w ON p.id = w.personid
WHERE (p.person = @id)

这个returns

我需要的是 0 < 年龄 <= 100 的所有行,年龄应为 0,并且应将这些行的总小时数相加。那么,对于100 < age <= 200,age为1,依此类推...

谢谢!

查询你的查询:

  SELECT     ((age - 1)/100) as AgeRange, sum(totalhours)
  FROM         yourquery
  group by ((age -1)/100)

尝试 - 这将给出包括出生月份在内的人的年龄

SELECT w.personid, Datediff(MM, Convert(date, birthdate, 112), Convert(date, p.date, 112))/12 AS age, Sum(w.hours) AS totalhours
FROM Person AS p INNER JOIN Workday AS w ON p.id = w.personid
WHERE (p.person = @id)
Group By w.personid, Datediff(MM, Convert(date, birthdate, 112), Convert(date, p.date, 112))/12
Order By w.personid, Datediff(MM, Convert(date, birthdate, 112), Convert(date, p.date, 112))/12