我有一个关于以表格形式获取数据的问题。我有一个单行的表现在我只想在给定逻辑的基础上增加数量.. 喜欢
1st row amount=1200,
2nd row amount=1320(1200+120),
3rd row amount=1452(1320+132)
逻辑是10%加上以前的金额
我的桌子是
Sno - Name- Amount
1 - A - 1200
现在我想要这样的结果..
Sno - Name- Amount
1 - A - 1200
2 - A - 1320
3 - A - 1452
任何人都可以帮助我,我找不到任何逻辑
答案 0 :(得分:4)
这与WadimX的答案完全相同,但它会做100行。要根据输入表(我将其称为example
)生成示例输出:
;WITH nums AS
(SELECT 1 AS RowNum, Name, Amount
FROM (SELECT Name, Amount FROM example) s
UNION ALL
SELECT RowNum + 1 As RowNum, Name, CAST(1.1*Amount AS INT) AS Amount
FROM nums
WHERE RowNum < 5)
SELECT RowNum AS SNo, Name, Amount
FROM nums
ORDER BY Name
为example
中的每条记录返回5行,您可以通过将RowNum < 5
更改为100
或者您想要的更多来增加该计数。
<强>输出强>
SNo Name Amount
-----------------------
1 A 1200
2 A 1320
3 A 1452
... ... ...
答案 1 :(得分:1)
WITH COUNTER(RN)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY object_id)
FROM sys.objects
),
A(RN, value)
AS
(
SELECT CAST(1 as bigint),
CAST(1200 as decimal(20, 0))
UNION ALL
SELECT COUNTER.RN,
CAST(A.value*1.1 as decimal(20, 0))
FROM COUNTER JOIN A ON A.RN=COUNTER.RN-1
)
SELECT TOP 1000 *
FROM A
OPTION(MAXRECURSION 1000)
此示例从sys.objects中选择前1000行。您应该将 sys.objects 替换为您的表名,将 object_id 替换为主/唯一键列。您还应该更改 TOP 1000 和 MAXRECURSION 1000 。注意MAXRECURSION可能介于0和32767之间,0 - 无限制。 注意大表,因为它会导致算术溢出值。
答案 2 :(得分:0)
这就是你要求的:
select sno, name, amount from table1
union select sno+1, name, amount*1.1 from table1
union select sno+2, name, amount*1.1*1.1 from table1
但它不是很灵活。例如。如果有多行,您可能会获得重复的'sno'数字。
答案 3 :(得分:0)
重新修改使用cte的答案:
DECLARE @T TABLE (sno INT, name CHAR(1), amount INT)
INSERT INTO @T
SELECT 1, 'a', 1200
;WITH cte AS (
SELECT sno, name, amount
FROM @T
WHERE sno = 1
UNION ALL
SELECT sno+1, name, amount + amount / 10
FROM cte
WHERE sno+1 <= 100
)
SELECT *
FROM cte
结果:
sno name amount
1 a 1200
2 a 1320
3 a 1452
4 a 1597
5 a 1756
6 a 1931