用于SELECT数字范围的查询

时间:2013-06-14 10:27:44

标签: sql sql-server select

我遇到以下问题。

我想从数据库中选择一个货币值,该值将作为查询最高结果的默认值(此部分已经完成,不是我主要问题的一部分)。

我想使用类似这样的查询:

SELECT valkurs, valkurs 'vk'
FROM xx
WHERE valkod='EUR' AND foretagkod=300
UNION
--(My problem is that i can't find out what to write here)

我的问题是我想在1.0到20.0之间附加一系列值,其中增量步长为0.1,与上面提到的原始查询相对应。

示例输出可能如下所示:

8.88, 8.88

1.0, 1.0

1.1, 1.1

1.2, 1.2

...

20.0, 20.0

无论如何都可能吗?

由于实施问题,这必须在查询中完成......

2 个答案:

答案 0 :(得分:4)

您可以使用系统表Master..spt_values生成顺序列表:

SELECT  Number = CAST(1 + (Number / 10.0) AS DECIMAL(4, 1)),
        Number2 = CAST(1 + (Number / 10.0) AS DECIMAL(4, 1))
FROM    Master..spt_values
WHERE   Type = 'P'
AND     Number BETWEEN 0 AND 200

因此,要以正确的顺序与您当前的查询组合,我会使用:

SELECT  valkurs, VK = valkurs
FROM    (   SELECT  valkurs, SortOrder = 0
            FROM    xx
            WHERE   valkod = 'EUR' 
            AND     foretagkod = 300
            UNION ALL
            SELECT  valkurs = CAST(1 + (Number / 10.0) AS DECIMAL(4, 1)), SortOrder = 1
            FROM    Master..spt_values
            WHERE   Type = 'P'
            AND     Number BETWEEN 0 AND 190
        ) T
ORDER BY T.SortOrder, t.valkurs;

<强>附录

有些人不提倡使用Master..spt_values,因为它没有记录,所以可以从未来版本的sql-server中删除。如果这是一个主要问题,您可以使用ROW_NUMBER()生成顺序列表(使用任何具有足够行的表作为源,我已经去了sys.all_objects):

SELECT  valkurs, VK = valkurs, 
FROM    (   SELECT  valkurs, SortOrder = 0
            FROM    xx
            WHERE   valkod = 'EUR' 
            AND     foretagkod = 300
            UNION ALL
            SELECT  TOP 191 
                    valkurs = 1 + ((ROW_NUMBER() OVER(ORDER BY object_id) - 1) / 10.0),
                    SortOrder = 1
            FROM    sys.all_objects
        ) T
ORDER BY T.SortOrder, t.valkurs;

答案 1 :(得分:1)

陈旧,但我认为有些人会从我的答案中受益,这是一个比接受的答案要好得多的实施

WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e1 CROSS JOIN e2), -- 10*100
numbers as (SELECT n = ROW_NUMBER() OVER (ORDER BY n)/10.0
FROM e3)
select n, n from numbers
where n between 1 and 20