日期:2014-05-18  浏览次数:20610 次

字段 比较 结果 写入 同行其他字段

SQL code

tab1
a1   a2   a3 
1    23    
2    63
3    43
4    53
5    66
6    67 


看a2是否含有3 有3输出结果1 无3输出结果0 在看a2是否含有6,有6输出结果1 无6输出结果0 2个结果进行相加 写入 同行 a3  

update tab1 ,(SELECT sum(if(a2 rlike 3,1,0))+
sum(if(a2 rlike 6,1,0)) as s
FROM tab1 GROUP BY a2
) c
set tab1.a3=c.s
这句 怎么 不行啊 什么问题出错了么

------解决方案--------------------
SQL code

IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')
BEGIN
    DROP TABLE tba
END
GO
CREATE TABLE tba
(
    a1 INT,
    a2 INT,
    a3 INT
) 

GO
INSERT INTO tba 
SELECT 1,23,0 UNION  
SELECT 2,63,0 UNION
SELECT 3,43,0 UNION
SELECT 4,53,0 UNION
SELECT 5,66,0 UNION
SELECT 6,67,0
GO

UPDATE tba SET a3 = CASE WHEN CHARINDEX('3',LTRIM(a2)) > 0 THEN 1
                         ELSE 0 END + CASE WHEN CHARINDEX('6',LTRIM(a2)) > 0 THEN 1
                                           ELSE 0 END 

SELECT * FROM tba

a1    a2    a3
1    23    1
2    63    2
3    43    1
4    53    1
5    66    1
6    67    1

------解决方案--------------------
SQL code

USE tempdb;
GO
IF OBJECT_ID('testtb') IS NOT NULL 
DROP TABLE testtb;
GO
CREATE TABLE testtb
(a1 INT IDENTITY(1,1),
 a2 INT NULL ,
 a3 INT NULL  
);
GO
INSERT INTO testtb VALUES(23,NULL);
INSERT INTO testtb VALUES(63,NULL);
INSERT INTO testtb VALUES(43,NULL);
INSERT INTO testtb VALUES(53,NULL);
INSERT INTO testtb VALUES(66,NULL);
INSERT INTO testtb VALUES(67,NULL);
GO




UPDATE dbo.testtb SET a3=(CASE WHEN PATINDEX('%3%',CAST(a2 AS CHAR(4)))<>0 THEN 1
                               ELSE 0 END)+
                          (CASE WHEN PATINDEX('%6%',CAST (a2 AS CHAR(4)))<>0 THEN 1
                           ELSE 0 END );
                         
SELECT * FROM dbo.testtb;
/*--结果
a1    a2    a3
1    23    1
2    63    2
3    43    1
4    53    1
5    66    1
6    67    1
*/