以下是生成正确输出的示例查询示例:
DECLARE @T TABLE (
keydate DATE,
price MONEY
);
INSERT INTO @T(keydate, price) VALUES
('2014-07-23', 32464),
('2014-07-26', 32478),
('2014-07-27', 32473)
;WITH
cte_tbl (keydate, price, prev_price1)
AS (
SELECT TOP(1)
T.keydate,
T.price,
T.price AS prev_price
FROM @T AS T
ORDER BY T.keydate
UNION ALL
SELECT
T.keydate,
T.price,
T.prev_price
FROM (
SELECT
TT.keydate,
TT.price,
IIF(ABS(TT.price - cte_tbl.prev_price1) < 10, cte_tbl.prev_price1, TT.price) AS prev_price,
ROW_NUMBER() OVER(ORDER BY TT.keydate) AS ROWNUM
FROM @T AS TT
INNER JOIN cte_tbl ON cte_tbl.keydate < TT.keydate
) AS T
WHERE T.ROWNUM = 1
)
SELECT *
FROM cte_tbl
ORDER BY keydate
正确输出为:
keydate price prev_price1
2014-07-23 32464.00 32464.00
2014-07-26 32478.00 32478.00
2014-07-27 32473.00 32478.00
如果我更改为以点为单位持有MONEY的十进制价格:
INSERT INTO @T(keydate, price) VALUES
('2014-07-23', 324.64),
('2014-07-26', 324.78),
('2014-07-27', 324.73)
输出错误:
keydate price prev_price1
2014-07-23 324.64 324.64
2014-07-26 324.78 324.64
2014-07-27 324.73 324.64
实际上价格在CTE声明中,但它不会拒绝混乱。
我需要将它们存储为正常价格并具有正确的输出行为,如上所述:
('2014-07-23', 324.64),
('2014-07-26', 324.78),
('2014-07-27', 324.73)
输出应为:
keydate price prev_price1
2014-07-23 32464.00 324.64
2014-07-26 32478.00 324.78
2014-07-27 32473.00 324.78
感谢您的帮助!
答案 0 :(得分:3)
这是因为32464
和32478' is more than 10, but the difference between
324.64 and
324.78`之间的差异不是。改变这一行:
IIF(ABS(TT.price - cte_tbl.prev_price1) < 10, cte_tbl.prev_price1, TT.price)
为:
IIF(ABS(TT.price - cte_tbl.prev_price1) < 0.10, cte_tbl.prev_price1, TT.price)
如果您将价格降低10倍,则需要将比较减少10倍。