[英]Column loop and update another column with COUNT() value from another table
This is my table events
这是我的餐桌
events
event name countBus
ev12 test NULL
ev16 paris NULL
and table klient
和桌子
klient
event name bus
ev12 bob True
ev12 Alice True
ev12 John False
ev16 Tom True
ev16 Peter False
What I'm trying to do is to loop through all rows of table events
and update amount of rows that is found in table klient
for particular event and bus=True
. 我想做的是遍历表
events
所有行,并更新在表klient
为特定事件和bus=True
找到的行数。 Then back update that value to particular row in table events
column countBus
. 然后将该值更新为表
events
列countBus
特定行。
Output of table event
would be 表
event
输出将是
ev12 test 2
ev16 paris 1
I'm sorry for not providing my attempt as I don't even know where to start. 很抱歉没有提供我的尝试,因为我什至不知道从哪里开始。
Thanks for spending your free time on this. 感谢您在此上花费您的空闲时间。
You could di it with a sub-select like this: 您可以使用以下子选择来进行编辑:
UPDATE events
SET countBus = (SELECT count(*)
FROM klient k
WHERE events.event = k.event
AND k.bus = 'True')
Or with a join, like this: 或使用联接,如下所示:
UPDATE e
SET countBus = t.countBus2
FROM events e
INNER JOIN (SELECT event, bus, COUNT(*) countBus2
FROM klient
WHERE bus = 'True'
GROUP BY event, bus) AS t
ON e.event = k.event
So to break this up and explain it a little you need to do two things really: 因此,要对此进行分解并进行一些解释,您实际上需要做两件事:
Query to get the count per event 查询以获取每个事件的计数
select e.event, e.name, count(bus)
from klient k
inner join events e on k.event = e.event
where k.bus = N'True'
group by e.event, e.name
Working Sample: SQL Fiddle 工作示例: SQL小提琴
The Update Query 更新查询
update events
set countBus = (select count(bus)
from klient k
where k.event = events.event and k.bus = N'True')
-- view the results
select * from events
Working Sample: SQL Fiddle 工作示例: SQL小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.