0

我有如下格式的表格,条件是 nvarchar 格式的值之间的年龄

Id  Condition
1   0 to 10
2   10 to 20
3   20 to 30
4   30 to 40
5   40 to 50
6   50 Above

现在我想在运行时检索 id 值年龄需要根据匹配边界与表条件列进行检查。

你能帮忙解决这个问题吗?

4

3 回答 3

3

我同意 SWeko。如果你不能改变类型,你似乎很幸运有一个简单的线性进展,所以这也可以。注意:这是一个非最佳解决方案

DECLARE @InputAge TINYINT = 31

;WITH MyTable (Id, Condition) AS
(
-- Corrected age overlaps
    SELECT 1, '0 to 10'     UNION ALL
    SELECT 2, '11 to 20'    UNION ALL
    SELECT 3, '21 to 30'    UNION ALL
    SELECT 4, '31 to 40'    UNION ALL
    SELECT 5, '41 to 50'    UNION ALL
    SELECT 6, '51 Above'
)
SELECT Id
FROM MyTable 
WHERE @InputAge BETWEEN 10 * Id-9 
                AND CASE WHEN Id = 6 THEN 150 ELSE 10*Id END

字符串操作操作将是这样的。这也是一个很差的表演者!

DECLARE @InputAge TINYINT = 35

;WITH MyTable (Id, Condition) AS
(
-- Corrected age overlaps
    SELECT 1, '0 to 10'     UNION ALL
    SELECT 2, '11 to 20'    UNION ALL
    SELECT 3, '21 to 30'    UNION ALL
    SELECT 4, '31 to 40'    UNION ALL
    SELECT 5, '41 to 50'    UNION ALL
    SELECT 6, '51 Above'
)
SELECT   Id
        ,LEFT(Condition, CHARINDEX(' ', Condition))
        ,RIGHT(Condition, CHARINDEX(' ', REVERSE(Condition)))
FROM MyTable 
WHERE @InputAge BETWEEN LEFT(Condition, CHARINDEX(' ', Condition)) AND ISNULL(NULLIF(RIGHT(Condition, CHARINDEX(' ', REVERSE(Condition))), 'Above'), 255)
于 2013-01-10T12:58:35.687 回答
2

如果您对表的结构有任何权力,请将其更改为一种(ID, MaxAge, MinAge)格式,然后您的查询类似于:

select p.*, r.ID as AgeBracket 
from people p
  inner join ageRestrictions r 
    on p.Age between r.MinAge and r.MaxAge

如果表格的结构是一成不变的,那么在问题中提及这一点。

于 2013-01-10T12:50:13.090 回答
0

您想重组该表并使用 SWekos 代码,但要直接回答您的问题:

如果它与您描述的完全一样,那么您可以在HELLUVA DIRTY HACK中利用年龄和范围 ID 之间的关系:

select 
    CASE p.age
      WHEN  p.age < 70 THEN p.age %10 + 1
      ELSE 6
FROM People as p

;)

于 2013-01-10T12:56:25.207 回答