我有一种情况,我需要在更新的where条件中使用聚合函数 声明和select语句。
示例:
Update test_table
set ID_Number = 0
where count(ID_Number)=1; /* Not possible with where */
注意:使用where子句无法使用上述脚本。
例如,我有下表:测试
ID_Number Column1 Column2
--------------------------
1 XYZ ZYX
1 MMM NNN
2 III JJJ
3 AAA BBB
3 CCC DDD
现在我只需要显示那些ID_Number出现两次的记录。
预期结果:
ID_Number Column1 Column2
------------------------------
1 XYZ ZYX
1 MMM NNN
3 AAA BBB
3 CCC DDD
我的尝试:
select * from Test
group by ID_Number,Column1,Column2
having count(ID_Number)>1;
注意:这对我没有任何帮助。
答案 0 :(得分:2)
SET NOCOUNT ON;
DECLARE @Test TABLE
(
ID_Number INT NOT NULL,
Column1 VARCHAR(50),
Column2 VARCHAR(50)
);
INSERT INTO @Test VALUES (1, 'XYZ', 'ZYX');
INSERT INTO @Test VALUES (1, 'MMM', 'NNN');
INSERT INTO @Test VALUES (2, 'III', 'JJJ');
INSERT INTO @Test VALUES (3, 'AAA', 'BBB');
INSERT INTO @Test VALUES (3, 'CCC', 'DDD');
-- Situation #1
;WITH cte AS
(
SELECT ID_Number
FROM @Test
GROUP BY ID_Number
HAVING COUNT(*) = 1
)
UPDATE ts
SET ts.ID_Number = 0
FROM @Test ts
INNER JOIN cte
ON cte.ID_Number = ts.ID_Number;
-- Situation #2
;WITH cte AS
(
SELECT ID_Number
FROM @Test
GROUP BY ID_Number
HAVING COUNT(*) > 1
)
SELECT ts.*
FROM @Test ts
INNER JOIN cte
ON cte.ID_Number = ts.ID_Number;
输出是问题中显示的“预期结果”。
对于这两种情况,CTE都会获得多次显示的ID_Number
值,并且该值列表用于过滤主SELECT
或UPDATE
。
答案 1 :(得分:0)
试试这个:
情况1:
更新你可以使用Common Table Expressions
Update test_table
set ID_Number = 0
where ID_Number IN (
select tst.ID_Number from test_table tst join
(
select ID_Number,COUNT(*) as CNT from test_table
GROUP BY ID_Number)d
ON d.ID_Number=tst.ID_Number
where d.CNT=1
)
情况2:
select tst.ID_Number,Column1,Column2 from test_table tst join
(
select ID_Number,COUNT(*) as CNT from test_table
GROUP BY ID_Number)d
ON d.ID_Number=tst.ID_Number
where d.CNT>1
答案 2 :(得分:0)
首先查看情境2 您的查询以获得所需的输出,如下所示:
SELECT * FROM Test
WHERE ID_Number IN (select ID_Number from Test
group by ID_Number
having count(ID_Number)>1)
现在查看情境1 ,您可以编写更新列的UPDATE查询 :ID_Number = 0仅适用于ID_Number根据您在更新查询中声明的记录一次的记录。您可以按如下方式修改更新查询:
Update test_table
set ID_Number = 0
FROM test_table
WHERE ID_Number IN (select ID_Number from Test
group by ID_Number
having count(ID_Number) = 1
答案 3 :(得分:0)
这就是我要做的事情:
with cte as (
select *, count(*) over (partition by ID_Number) as c
from test_table
)
select *
from cte
where c > 1