仍在处理表和查询,但在SQL Server查询方面需要一些帮助。
我有一张看起来像这样的桌子。
VMName | DiskType | Status | Result
---------+------------+-------------+---------
TestVM1 | OS | Completed |
TestVM1 | Data | Completed |
TestVM2 | OS | Failed |
TestVM2 | Data | Completed |
TestVM2 | Data | Completed |
在结果列中,如果操作系统和数据磁盘的状态都为“完成”,我想将其说为“已完成”。
但是,如果OS磁盘显示失败,则该VM的所有磁盘的结果列应显示失败。
喜欢这个。
VMName | DiskType | Status | Result
---------+------------+-------------+---------
TestVM1 | OS | Completed | Completed
TestVM1 | Data | Completed | Completed
TestVM2 | OS | Failed | Failed
TestVM2 | Data | Completed | Failed
TestVM2 | Data | Completed | Failed
我尝试将一个查询合并在一起,但是不知道我在做什么错,因为它什么也没做。
UPDATE working_table t1
SET Result = 'Failed'
WHERE disktype = 'OS' AND
status = 'Failed' AND
NOT EXISTS (SELECT 1 FROM working_table t2 WHERE t1.VMname = t2.VMname);
答案 0 :(得分:2)
似乎只需要一个EXISTS
UPDATE t1
SET Result = 'Failed'
FROM working_table t1
WHERE EXISTS (
SELECT 1
FROM working_table t2
WHERE t2.VMname = t1.VMname
AND t2.disktype = 'OS'
AND t2.[Status]= 'Failed'
);
或者,如果您想更新所有结果,不仅是那些失败的结果:
UPDATE t1
SET Result = CASE
WHEN EXISTS (SELECT 1 FROM working_table t2 WHERE t2.VMname = t1.VMname AND t2.disktype = 'OS' AND t2.[Status] = 'Failed')
THEN 'Failed'
ELSE t1.[Status]
END
FROM working_table t1;
答案 1 :(得分:1)
请尝试
create table working_table
(
VMName varchar(30),
DiskType varchar(64),
[Status] varchar(30),
Result varchar(64)
)
insert into working_table values
('TestVM1','OS','Completed',NULL),
('TestVM1','Data','Completed',NULL),
('TestVM2','OS','Failed',NULL),
('TestVM2','Data','Completed',NULL),
('TestVM2','Data','Completed',NULL)
;WITH CTE AS
(
SELECT
*,
SUM(CASE [Status] WHEN 'Failed' THEN 1 ELSE 0 END) OVER (partition by VMName) as v_flag
FROM working_table
)
UPDATE CTE SET Result=CASE WHEN v_flag >0 THEN 'Failed' ELSE 'Completed' END
--Query
SELECT * FROM working_table
--Output
/*
VMName DiskType Status Result
------------------------------ ---------------------------------------------------------------- ------------------------------ ----------------------------------------------------------------
TestVM1 OS Completed Completed
TestVM1 Data Completed Completed
TestVM2 OS Failed Failed
TestVM2 Data Completed Failed
TestVM2 Data Completed Failed
*/
最好的问候,
会
答案 2 :(得分:0)
此查询可能会对您有所帮助。
SELECT *,MAX(status)
OVER (
partition BY vmname
ORDER BY vmname ) [Results]
FROM working_table
您可以根据此结果更新表格