在SQL表中添加和插入相同ID的值 [英] Adding and inserting values of same ID in sql table

查看:110
本文介绍了在SQL表中添加和插入相同ID的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在编写能准确满足我需要的查询时遇到麻烦.
我有一张像下面的桌子

 Id日期值累计
1月1日1日0.2
1月2日1日0.5
1月2日0.7
1月2日0.6
1月2日0.1
1月3日0.02
1月3日0.01
1月3日0.03 



我想编写一个查询,该查询插入具有相同ID的值之和的累积列,即

 Id累计
1 0.2
2 0.5
1 0.9(0.2 + 0.7)
2 1.1(0.5 + 0.6)
4 0.1
1 0.92(0.2 + 0.7 + 0.02)
3 0.01
4 0.13(0.1 + 0.03)



在此先谢谢您.

解决方案

如果您有一个附加的序列列(例如UniqeID),这将很容易.如果有的话,就可以这样

 更新 CumulativeTable
     SET 累积=值+(选择 Sum(Value)累积表其中 UniqueID< c.UniqueID
                         AND  ID = c.ID)
来自 CumulativeTable c 



或者如果没有,可以尝试一下,


  DECLARE   @ TempTable   TABLE (唯一ID  int   IDENTITY ,
ID  int ,
值数字( 18  3 ),
累积数字( 18  3 )
)

 DECLARE   @ TempTable   TABLE (唯一ID  int   IDENTITY ,
ID  int ,
值数字( 18  3 ),
累积数字( 18  3 )
)

插入 插入  @ TempTable (ID,值,累计)
选择 ID,值,累积累积表

更新 CumulativeTable
 SET 累积=  COALESCE (c.Value +( Select  Sum(Value)来自  @ TempTable  其中 UniqueID< c.UniqueID
 AND  ID = c.ID), 0 )
来自 CumulativeTable t, @ TempTable  c
位置 t.ID = c.ID  AND  t.Value = c.Value 




但是如果您有多个具有相同ID和值的记录,这将无法为您提供正确的值

Hi,
I am having trouble writing a query that accurately does what I need.
I have a table like the following

Id    Date        Value     Cumulative
1     Jan 1st       0.2
2     Jan 1st       0.5
1     Jan 2nd       0.7
2     Jan 2nd       0.6
4     Jan 2nd       0.1
1     Jan 3rd       0.02
3     jan 3rd      0.01
4     Jan 3rd      0.03



I want to write a query which inserts the cumulative column with the sum of the value for the same Ids i.e.,

Id     Cumulative
1        0.2
2        0.5
1        0.9  (0.2+0.7)
2        1.1  (0.5+0.6)
4        0.1
1        0.92  (0.2+0.7+0.02)
3        0.01
4        0.13  (0.1 + 0.03)



Thanks in advance.

解决方案

It would be easy if you have an additional sequence column (e.g. UniqeID). If you have, you can just have it this way

Update CumulativeTable
    SET Cumulative = Value + (Select Sum(Value) From CumulativeTable Where UniqueID < c.UniqueID
                        AND ID = c.ID)
From CumulativeTable c



or if you don''t have, you can try this,


DECLARE @TempTable TABLE (UniqueID int IDENTITY,
ID int,
Value numeric(18,3),
Cumulative numeric(18,3)
)

DECLARE @TempTable TABLE (UniqueID int IDENTITY,
ID int,
Value numeric(18,3),
Cumulative numeric(18,3)
)

Insert Into @TempTable (ID, Value, Cumulative)
Select ID, Value, Cumulative From CumulativeTable

Update CumulativeTable
	SET Cumulative = COALESCE(c.Value + (Select Sum(Value) From @TempTable Where UniqueID < c.UniqueID
						AND ID = c.ID),0)
From CumulativeTable t, @TempTable c
Where t.ID = c.ID AND t.Value = c.Value




but this will not give you correct value if you have multiple records with the same ID and value


这篇关于在SQL表中添加和插入相同ID的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆