1

我遇到以下问题。

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

我想使用如下所示的查询:

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)

我的问题是,我想以增量步骤将 0.1 的值范围从 1.0 到 20.0 附加到上面提到的原始查询中。

示例输出如下所示:

8.88, 8.88

1.0, 1.0

1.1, 1.1

1.2, 1.2

...

20.0, 20.0

有可能吗?

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

4

2 回答 2

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;
于 2013-06-14T10:39:17.623 回答
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
于 2014-06-23T23:38:42.530 回答