有个表里面有个字段:unit ,里面大部分的值是数字,但有很小一部分有字符,如下:
id unit
12 201+1
12 20
12 321
15 3/PNL
15 /
15 23
15 658.1
要做到以下效果:
1. 有 “ + ” 符号的情况,例:201+1 要将结果加在一起:202
2. 发现数字有小数点的,省去小数点。
3. 有 “ /PNL ” 或者 “ / PNL ”的情况,替换成空。如果是:3/PNL ,要得到 3;“ /PNL ”,得到0 。
4. 有 “ / ” 符号的情况(单独),替换成空,或者0.
5. 1,4丙种情况处理后,将数据加起来,再乘以一个数字,比如 2.
6. 2,3两种情况处理后,将数据加起来即可。
7. 将5,6得到的数值求和。
最终效果应该是:
id unit
12 1086 --(202 + 20 + 321)* 2=1086
15 1365 --(658 + 23)*2 + 3 + 0 =1365
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2013-11-22 16:44:32
-- Verstion:
-- Microsoft SQL Server 2012 - 11.0.2100.60 (X64)
-- Feb 10 2012 19:39:15
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[unit] varchar(5))
insert [tb]
select 12,'201+1' union all
select 12,'20' union all
select 12,'321' union all
select 15,'3/PNL' union all
select 15,'/' union all
select 15,'23' union all
select 15,'658.1'
--------------开始查询--------------------------
IF object_id('tempdb..#tb') IS NOT NULL
DROP TABLE #tb
go
CREATE TABLE #tb
(
[id] int,[unit] varchar(5)
)
go
INSERT INTO #tb SELECT id,unit FROM tb WHERE LEN(unit)-LEN(REPLACE(REPLACE(REPLACE(unit,'/PNL',''),'.',''),'/',''))>0
SELECT id,
CASE WHEN CHARINDEX('/PNL',unit)>0 THEN LEFT(unit,CHARINDEX('/PNL',unit)-1)
WHEN CHARINDEX('/',unit)>0 THEN 0
WHEN CHARINDEX('.',unit)>0 THEN CAST(REPLACE(unit,'.','')/10 AS INT)
END AS unit INTO #tb1 FROM #tb
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+'select ID='+ltrim(ID)+', unit=2*('+unit+') union all ' from (SELECT * FROM tb a WHERE NOT EXISTS(SELECT 1 FROM #tb WHERE unit=a.unit))a
set @sql=left(@sql,len(@sql)-10)
SET @sql='select id,sum(unit) as unit from(select * from ('+@sql+') as a union all (select * from #tb1))t group by id'
EXEC(@sql)
DROP TABLE #tb1
----------------结果----------------------------
/* id unit
----------- -----------
12 1086
15 707
(2 行受影响)
*/
你的结果有问题?
------解决方案--------------------
是这样吗:
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[unit] varchar(5))
insert [tb]
select 12,'201+1' union all
select 12,'20' union all
select 12,'321' union all
select 15,'3/PNL' union all
select 15,'/' union all
select 15,'23' union all