声明和循环时的情况?

时间:2012-07-23 00:33:04

标签: sql sql-server-2008 tsql

所以我被告知循环在SQL中不是一件理想的事情。以下问题根据年龄范围制作直方图。如您所见,所有组都是硬编码的。在这种情况下,我正在寻找的所有值都在100以下。如果这些值达到数千个,该怎么办?如何才能使其更具可扩展性?

select bins, count(*) as numbers from
(

select id, patientage,
case 
    when patientage between 20 and 29 then '20-29' 
    when patientage between 30 and 39 then '30-39'
    when patientage between 40 and 49 then '40-49'
    when patientage between 50 and 59 then '50-59'
    when patientage between 60 and 69 then '60-69'
    when patientage between 70 and 79 then '70-79'
    when patientage between 80 and 89 then '80-89'
    when patientage between 90 and 99 then '90-99'


end as bins
from patient
inner join tblhospitals on tblhospitals.hospitalnpi=patient.hospitalnpi
where (tblhospitals.hospitalname like '%university%')
) as t
group by bins
order by bins

3 个答案:

答案 0 :(得分:2)

这是一个稍微通用的形式,可以替换为其他值:

select
    cast(
        patientage / cast(bucketsize as int)
            * cast(bucketsize as int) as varchar(10)) + '-' +
    cast(
        patientage / cast(bucketsize as int)
            * cast(bucketsize as int) + cast(bucketsize as int) - 1 as varchar(10))
...

答案 1 :(得分:1)

而不是您的case语句,您可以改为按patientage / 10分组。例如,如果您将查询重写为:

SELECT bins, COUNT(*) AS numbers
FROM (
    SELECT id, patientage, patientage / 10 AS bins
    FROM patient P
        INNER JOIN tblhospitals H ON H.hospitalnpi = P.hospitalnpi
    WHERE H.hospitalname LIKE '%university%'
) AS T
GROUP BY bins
ORDER BY bins

您将获得相同的数据,除了代替'50 -59',您将得到5,这实际上只是一个可以在SQL之外处理的显示问题。 (或者,如果你真的必须,你可以做一些数据按摩用于显示目的,如铸造箱* 10和箱* 10 + 9到varchar等)

答案 2 :(得分:0)

有人可能会稍微清理一下,但想法是

select CAST(patientage/ 10 * 10 as varchar) + ' - ' + CAST((patientage/ 10 * 10) + 9 as varchar) as bins