SQL在行

时间:2016-08-29 06:50:42

标签: sql sql-server

我有3行数据,并希望在行之间添加值。在excel中我可以使用excel公式并手动创建,但我想在SQL中创建它。预期结果如图像:

enter image description here

在图片中,F3是获取ID 1和2之间的平均值并将其除以10.获得平均值后,使用E3中的第一个值并添加值F3,得到1.271111。 E5使用E4加值F3等。

我想在不同的ID之间添加额外的10行,并根据ID之间的差值,将前一个值与差值相加。是不是可以在SQL语句中执行它?

2 个答案:

答案 0 :(得分:2)

我对你的平均水平感到困惑。

SELECT (10 - 0.18) / 9 -- 1.091111 -- This is your average?
--
SELECT (10 - 0.18) / 10 -- 0.982000000
SELECT (32.11 - 10) / 10 -- 2.211000

您可以如下所示:

DECLARE @Tbl TABLE (Id INT, Value DECIMAL(7, 5))
INSERT INTO @Tbl        
VALUES  
(1, 0.18),
(2, 10),
(3, 32.11)

;WITH CTE
AS 
(
    SELECT 
        Id ,
        Value, 
        COALESCE((LEAD(Value) OVER (ORDER BY Id) * 1.0 - Value * 1.0) / 10, 0) AS AverageValue
    FROM @Tbl
)

--SELECT (10 - 0.18) / 10 -- 0.982000000
--SELECT (32.11 - 10) / 10 -- 2.211000

SELECT DISTINCT 
    A.Id,
    COALESCE((B.RowId * 1.0 * A.AverageValue) + A.Value,0) AS Result
FROM
    CTE A CROSS JOIN
    (VALUES(0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) B(RowId) 

注意:这是针对2012 +

答案 1 :(得分:1)

您需要递归CTE:

;WITH YourTable AS ( --simulation of your table
    SELECT * FROM (VALUES (1,0.18),(2,10),(3,32.11)) as t(Id,[Value])
), cte AS ( --Don't know what version of SQL Server you are using
    SELECT  a.ID,   --so I use OUTER APPLY to get next string value
            cast(a.[Value] as float) [Value],
            ISNULL(CAST((b.[Value]-a.[Value])/10 as float),0.00) as Seq
    FROM YourTable a
    OUTER APPLY (
        SELECT TOP 1 *
        FROM YourTable
        WHERE a.ID < ID
        ORDER BY ID ASC
        ) b
), final AS (
    SELECT  c.ID,
            c.[Value],
            c.Seq
    FROM cte c
    UNION ALL
    SELECT  CASE WHEN f.[Value]+f.Seq = c.[value] THEN c.id ELSE f.id END,
            f.[Value]+f.Seq,
            CASE WHEN ROUND(f.[Value]+f.Seq,2) = ROUND(c.[value],2) THEN c.Seq ELSE f.Seq END
    FROM final f
    INNER JOIN cte c
        ON c.ID = f.ID+1 and
             ROUND(f.[Value]+f.Seq,2) < ROUND(c.[value],2)
    WHERE f.seq > 0 
)

SELECT  ROW_NUMBER() OVER (ORDER BY [Value]) as ID,
        [Value],
        Seq
FROM final
ORDER BY id,[Value]
OPTION (MAXRECURSION 200)

输出:

ID  Value   Seq
1   0,18    0,982
2   1,162   0,982
3   2,144   0,982
4   3,126   0,982
5   4,108   0,982
6   5,09    0,982
7   6,072   0,982
8   7,054   0,982
9   8,036   0,982
10  9,018   0,982
11  10      2,211
12  12,211  2,211
13  14,422  2,211
14  16,633  2,211
15  18,844  2,211
16  21,055  2,211
17  23,266  2,211
18  25,477  2,211
19  27,688  2,211
20  29,899  2,211
21  32,11   0