尝试制作一个能够计算我所拥有的问题数量并使用正确的WHERE子句
的表格 create table #test(
BatchNo int,
Q varchar(MAX),
number varchar(MAX),
DayNo varchar(MAX),
total int
)
INSERT INTO #test ( BatchNo, Q,number, DayNo, total ) VALUES
( 2, 'A','1', '1', NULL ),
( 2, 'A','1', '1', NULL ),
( 8, 'A','3', '1', NULL ),
( 8, 'A','3', '1', NULL ),
( 99, 'A','4', '1', NULL ),
( 200, 'A','3', '1', NULL ),
( 200, 'A','3', '1', NULL ),
( 200, 'A','3', '1', NULL )
我使用了这个UPDATE因为某些原因GROUP BY Batchno不能使用UPDATE
UPDATE #test set total= (select count(batchno)as total from #test where (number=1 or number=3) and DayNo=1)
select * from #test
drop table #test
我不断得到这个结果
batchno | Q | number | DayNo | total
2 A 1 1 7
2 A 1 1 7
8 A 3 1 7
8 A 3 1 7
99 A 4 1 7
200 A 3 1 7
200 A 3 1 7
200 A 3 1 7
当我使用“SELECT * FROM #test”
时,我想得到一些看起来像这样的东西 batchno | Q | number | DayNo | total
2 A 1 1 2
2 A 1 1 2
8 A 3 1 2
8 A 3 1 2
99 A 4 1 null
200 A 3 1 3
200 A 3 1 3
200 A 3 1 3
答案 0 :(得分:2)
我想你想要:
UPDATE #test
set total = (select count(batchno)as total
from #test t2
where t2.batchno = t.batchno and (number=1 or number=3) and DayNo=1)
from #test t;
答案 1 :(得分:1)
你非常接近,只需使用一个temptable来保存每个BatchNo的计数并使用它。请试试这个:
select BatchNo,count(*) as total
into #temp
from #test t1
where (number=1 or number=3) and DayNo=1
Group by BatchNo
UPDATE #test
set total= (select total
from #temp t
where t.BatchNo = #test.BatchNo)
答案 2 :(得分:0)
我认为您可以使用窗口功能:
select t.*, count(*) over(partition by batchno) as total
from #test
答案 3 :(得分:-1)
在子集中,要对集合应用更新,您的条件是将所有值设置为等于该子查询。您可能需要考虑更新的where子句或使用可以与表连接的CTE。
;with cte as (
select count(batchno)as total --this will be sigma of all batchno, my bad...
from @test
where (number=1 or number=3) and DayNo=1
)
update @test
set total = (select total from cte)
where (number=1 or number=3) and DayNo=1