我的桌子如下所示
col1 california florida hawaii date
=================================================
a1 32 86 23 Jan
a2 67 63 8990 Jan
a3 86 453 6 Jan
b1 54 876 7868 Jan
b2 6 786 75 Jan
b3 988 56 876 Jan
c1 1 2344 6 Jan
c2 876 57 986 Jan
c3 12 67 76 Jan
a1 0 0 0 feb
a2 0 0 0 feb
a3 0 0 0 feb
b1 0 0 0 feb
b2 0 0 0 feb
b3 0 0 0 feb
c1 1 3 67 feb
c2 9 7 32 feb
c3 12 67 76 feb
a1 0 0 0 mar
a2 0 0 0 mar
a3 0 0 0 mar
b1 0 0 0 mar
b2 0 0 0 mar
b3 0 0 0 mar
c1 66 2 9 mar
c2 32 7 1 mar
c3 12 67 76 mar
现在我想为每个状态更新每个a1 = b1 = c1和a2 = b2 = c2和a3 = b3 = c3(如果它们是空的)
我想要每月给出如下所示的逻辑
if(a1==0) then a1=c1
if(a2==0) then a2=c2
if(a3==0) then a3=c3
if(b1==0) then b1=c1
if(b2==0) then b2=c2
if(b3==0) then b3=c3
如何为此编写查询..?
我需要的输出是
col1 california florida hawaii date
=================================================
a1 32 86 23 Jan
a2 67 63 8990 Jan
a3 86 453 6 Jan
b1 54 876 7868 Jan
b2 6 786 75 Jan
b3 988 56 876 Jan
c1 1 2344 6 Jan
c2 876 57 986 Jan
c3 12 67 76 Jan
a1 1 3 67 feb
a2 9 7 32 feb
a3 12 67 76 feb
b1 1 3 67 feb
b2 9 7 32 feb
b3 12 67 76 feb
c1 1 3 67 feb
c2 9 7 32 feb
c3 12 67 76 feb
a1 66 2 9 mar
a2 32 7 1 mar
a3 12 67 76 mar
b1 66 2 9 mar
b2 32 7 1 mar
b3 12 67 76 mar
c1 66 2 9 mar
c2 32 7 1 mar
c3 12 67 76 mar
答案 0 :(得分:1)
您可以使用CTE执行UPDATE
:
;WITH ToUpdate AS (
SELECT t1.col1, t1.california, t1.florida, t1.hawaii, t1.[date],
t2.california AS california_2, t2.florida AS florida_2, t2.hawaii AS hawaii_2
FROM mytable AS t1
JOIN mytable AS t2
ON t1.[date] = t2.[date] AND
(((t1.col1 IN ('a1', 'b1')) AND (t2.col1 = 'c1')) OR
((t1.col1 IN ('a2', 'b2')) AND (t2.col1 = 'c2')) OR
((t1.col1 IN ('a3', 'b3')) AND (t2.col1 = 'c3')))
WHERE t1.california = 0 AND t1.florida = 0 AND t1.hawaii = 0 AND
t1.col1 IN ('a1', 'a2', 'a3', 'b1', 'b2', 'b3')
)
UPDATE ToUpdate
SET california = california_2,
florida = florida_2,
hawaii = hawaii_2
答案 1 :(得分:0)
老实说,我宁愿只是将你所拥有的数据重复插入到一个新表中:
CREATE PROC YourProc
DECLARE @Loop INT
AS
SET @Loop = 2
WHILE @Loop > 0
BEGIN
INSERT INTO newTable (col1, california, florida, hawaii)
SELECT DISTINCT col1, california, florida, hawaii
FROM yourTable
SET @Loop = @Loop - 1
END