我有一个带有字段的表Tbl1:description,Dtype,valueLeft,valueRight 数据可能是这样的:
+----------------------------------------------+
| Description | Dtype | valueLeft | valueRight |
+----------------------------------------------+
| Art1 | 1 | 5 | 0 |
| Art2 | 1 | 3 | 0 |
| Art3 | 2 | 0 | 6 |
| Art4 | 1 | 11 | 0 |
| Art5 | 2 | 0 | 1 |
| ArtN | .... | .... | .... |
+..............................................+
字段Dtype只能是1或2
问题:我想用新值列进行SELECT值,其值为SUM值左移或值右值取决于字段Dtype的值(1 = sum valueLeft,2 =扣除valueRight)
示例:
+----------------------------------------------+
| Description | Dtype | valueLeft | valueRight | newcol
+----------------------------------------------+
| Art1 | 1 | 5 | 0 | 5
| Art2 | 1 | 3 | 0 | 8
| Art3 | 2 | 0 | 6 | 2
| Art4 | 1 | 11 | 0 | 13
| Art5 | 2 | 0 | 1 | 10
我该怎么做?
答案 0 :(得分:0)
由于您没有使用SQL Server
语法指定RDBMS ...
SELECT a.Description, a.Dtype, a.valueLeft, a.valueRight,
(SELECT SUM (CASE WHEN b.Dtype = 1 THEN b.valueLeft ELSE -b.valueRight END)
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY Description) as id, Dtype, valueLeft, valueRight
FROM Tbl1 ) b
WHERE b.id <= a.id)
FROM (SELECT ROW_NUMBER() OVER (ORDER BY Description) as id, Description, Dtype, valueLeft, valueRight
FROM Tbl1 ) a