我有两张桌子
Person(id, birthdate)
和
Workday(personid, date, hours)
birthdate
和date
都位于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 <0的所有行。年龄<= 100,年龄应为0,并且应将这些行的总小时数相加。然后,对于100&lt;年龄<= 200,年龄为1,依此类推......
谢谢!
答案 0 :(得分:2)
查询您的查询:
SELECT ((age - 1)/100) as AgeRange, sum(totalhours)
FROM yourquery
group by ((age -1)/100)
答案 1 :(得分: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