안녕하세요.
저는 현업으로 SQL은 WHERE절을 써서 기본적인 데이터 조회하고, 간략한 업데이트만 가끔 작업하고 있습니다.
작업을 하다가 막히는 부분이 있어서 질문드립니다.
ID | 성별 | 연도 | 품목 | Value |
1 | 1 | 2016 | A | 1 |
2 | 1 | 2015 | A | 1 |
3 | 1 | 2016 | A | 1 |
4 | 1 | 2016 | A | 1 |
5 | 1 | 2016 | A | 1 |
1 | 1 | 2016 | B | 1 |
2 | 1 | 2016 | B | 1 |
3 | 1 | 2016 | B | 2 |
4 | 1 | 2016 | B | 3 |
5 | 1 | 2016 | B | 3 |
위 테이블이 저희 데이터 구조입니다.
제가 하고 싶은 일은 품목 A=1 이면서 품목 B=3인 경우에 품목 A의 value를 5로 업데이트하고자 하는 것입니다.
(위 테이블의 ID=4,5 and 품목 A에 해당)
구글링을 통해 이것 저것 해봤는데 도무지 답이 나오지 않네요.
도움 부탁드립니다.
감사합니다.
Comment 3
-
ilovejsp
2016.06.23 15:31
-
ilovejsp
2016.06.23 15:32
value가 1자리수라고 생각하고 query만들었습니다. 참조하시길...
-
가마우지
2016.06.23 17:04
쿼리짜봤는데 위에 분과 거진 비슷하네요. ㅎㅎ
다른점이라면 tCode='A' and tVal='1 과 tCode='B' and tVal='3' 를 미리조회하여 각각 테이블로 만들고 조인하여 결과값을 가져오는 부분 정도네요.
CREATE TABLE dbo.tProduct
BEGIN TRAN
( tId int NULL
, tSex char(1) NULL
, tYear char(4) NULL
, tCode char(1) NULL
, tVal varchar(5) NULL
)
INSERT INTO tProduct VALUES(1,'1','2016','A','1')
INSERT INTO tProduct VALUES(2,'1','2015','A','1')
INSERT INTO tProduct VALUES(3,'1','2016','A','1')
INSERT INTO tProduct VALUES(4,'1','2016','A','1')
INSERT INTO tProduct VALUES(5,'1','2016','A','1')
INSERT INTO tProduct VALUES(1,'1','2016','B','1')
INSERT INTO tProduct VALUES(2,'1','2016','B','1')
INSERT INTO tProduct VALUES(3,'1','2016','B','2')
INSERT INTO tProduct VALUES(4,'1','2016','B','3')
INSERT INTO tProduct VALUES(5,'1','2016','B','3')
INSERT INTO tProduct VALUES(1,'2','2015','B','3')
UPDATE p1 SET
p1.tVal='5'
FROM (SELECT * FROM tProduct WHERE tCode='A' and tVal='1') as p1 INNER JOIN
(SELECT * FROM tProduct WHERE tCode='B' and tVal='3') as p2 ON p1.tId=p2.tId
WHERE p1.tSex=p2.tSex and p1.tYear=p2.tYear
COMMIT TRAN
오랜만에 답변다네요 ..ㅋㅋ
use tempdb
DROP TABLE TEST
GO
create table test
(
id int ,
gender int,
year varchar(4),
product char(1),
value int
)
GO
insert into test values(1,1,'2016','A',1)
insert into test values(2,1,'2016','A',1)
insert into test values(3,1,'2016','A',1)
insert into test values(4,1,'2016','A',1)
insert into test values(5,1,'2016','A',1)
insert into test values(1,1,'2016','B',1)
insert into test values(2,1,'2016','B',1)
insert into test values(3,1,'2016','B',2)
insert into test values(4,1,'2016','B',3)
insert into test values(5,1,'2016','B',3)
GO
SELECT * FROM TEST
--update query
UPDATE TEST
SET TEST.VALUE=5
FROM
(
SELECT BB.* FROM
(
select id,gender,year,product+''+convert(varchar(1),value) as productvalue
from test
) AS AA
INNER JOIN
(
select id,gender,year,product+''+convert(varchar(1),value) as productvalue
from test
) AS BB
ON AA.ID=BB.id
WHERE substring(AA.productvalue,1,1)='B' AND substring(AA.productvalue,2,1)='3'
AND substring(BB.productvalue,1,1)='A' AND substring(BB.productvalue,2,1)='1'
)AS CC
INNER JOIN TEST
ON TEST.ID=CC.ID AND TEST.gender=CC.gender AND TEST.product=SUBSTRING(CC.productvalue,1,1) AND TEST.year=CC.year AND TEST.value=SUBSTRING(CC.productvalue,2,1)