我在SQL Server中有一个包含付款数据的字符串列。该列包含两个以逗号分隔的数据,但有时可能只包含一个。我需要能够将这一列拆分为两个新列并将其转换为金钱并执行两者之和。
样本付款栏
+---------+
| Payment |
+---------+
| 1000 |
+---------+
| 500, 100|
+---------+
| 10,20 |
+---------+
期望的输出
+---------+---------+--------+-------+
| Payment | split1 | split2 | total |
+---------+---------+--------+-------+
| 1000 | 1000 | 0 | 1000 |
+---------+---------+--------+-------+
| 500, 100| 500 | 100 | 600 |
+---------+---------+--------+-------+
| 10,20 | 10 | 20 | 30 |
+---------+---------+--------+-------+
我希望在不使用函数的情况下在单个select语句中进行查询。
解决方案
我根据评论员提供的链接制定了解决方案。因为我不想使用游标或函数,所以这里是完整的select语句来回答我的问题:
SELECT
cast(substring('1000,789',1,CHARINDEX(',', '1000,789')-1) as decimal(10,2)) AS Payment1,
cast(substring('1000,789',CHARINDEX(',', '1000,789')+1,len('1000,789')) as decimal(10,2))
as Payment2,
cast(substring('1000,789',1,CHARINDEX(',', '1000,789')-1) as decimal(10,2)) +
cast(substring('1000,789',CHARINDEX(',', '1000,789')+1,len('1000,789')) as decimal(10,2))
as TotalPayment from payment;