查询日期分组?

时间:2017-07-29 20:41:16

标签: sql-server

我有一个Client表,其中包含行中的基本人口统计信息和具有DATE数据类型的出生日期(DOB)。

我正在尝试进行查询以获取我的条目,并计算年龄在18-60岁,61-79岁,80岁以上的客户数量。我不确定我是否有脑屁,但我无法弄清楚如何从我的桌子上收集这些信息......

所以我拥有的是:

to go

  let x true
  set top ifelse-value ( x ) 
  ["x is true"] 
  ["x is NOT true"]
  print ( word "Example 1:  " top )

  set top ifelse-value ( this-is-true ) 
  ["Reporter returned true"] 
  ["Reporter did not return true"]
  print ( word "Example 2:  " top )

  set x nobody
  set top ifelse-value ( x = nobody ) 
  ["x IS nobody"] 
  ["Is NOT nobody"]
  print ( word "Example 3:  " top )

  set x 0
  set top ifelse-value ( x = nobody ) 
  ["x IS nobody"] 
  ["x Is NOT nobody"]
  print ( word "Example 4:  " top )

  set top ifelse-value ( nobody = nobody ) 
  ["nobody = nobody"] 
  ["nobody != nobody"]
  print ( word "Example 5:  " top )

end

to-report this-is-true
  report true
end

我想要的是:

Last Name   First Name   DOB
Stein      Ethel       1954-01-20
Frank      Sam         1981-05-65
etc...

有什么建议要继续吗?

1 个答案:

答案 0 :(得分:3)

使用@ Alex的建议

declare @today datetime
set @today =getdate()


select 
 s as [start],
 e as [end], 
count(1) as [count]
from Client join
(values (0,17),(18,60),(61,79),(80,9999)) as ranges(s,e)
  on datediff(yy,dob,@today) between s and e
-- where buildingid=1
group by s,e

See demo here