用于查找每个生命年中一个人工作了多少小时的SQL查询

时间:2015-01-28 11:52:40

标签: sql sql-server sql-server-2014-express

我有两张桌子

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)

返回

Query return table

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

谢谢!

2 个答案:

答案 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