0

我有两张桌子

Person(id, birthdate)

Workday(personid, date, hours)

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

我需要一个查询,该查询返回一个表,其中包含一个人的年龄(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)

这返回

查询返回表

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

谢谢!

4

2 回答 2

2

Query over your query:

  SELECT     ((age - 1)/100) as AgeRange, sum(totalhours)
  FROM         yourquery
  group by ((age -1)/100)
于 2015-01-28T12:07:33.773 回答
0

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

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
于 2015-01-28T12:41:22.800 回答