SQL Server将频率列添加到现有表

时间:2016-05-17 19:36:11

标签: sql-server

如果我有一个包含重复值的列的表。如何向该表添加一列,以显示表中包含该值的条目数。

我知道你可以使用:

    select id, COUNT(id) as freq
    from mytable
    group by id
    order by freq desc

获取频率,但如何在原始表格的新列中显示?

2 个答案:

答案 0 :(得分:2)

它取决于您插入/更新/删除该表的频率,以及您需要选择它的频率。

我可能会像Joe C所说的那样认同。

但是,如果您不经常插入/更新/删除,并且您真的非常想要它,那么您可以在插入,更新和删除时执行触发操作,以便在需要时计算信息至。它应该是悲惨的插入,更新和删除性能,所以请记住:

create trigger dbo.MyTable_IUD
on dbo.MyTable
after insert, update, delete
as
begin
    update m
    set _freq = counts.freq
    from dbo.MyTable m
    join
    (
        select id, count(1) [freq]
        from dbo.MyTable
        where id in
        (
           select id from inserted 
           union select id from deleted
        )
        group by id
    ) counts on m.id = counts.id;
end;
go

答案 1 :(得分:1)

如果您需要这样做,我建议您创建一个视图。

Create View vMyTable As
Select M.*, F.Freq 
   From MyTable M 
   Join (Select id, Count(id) Freq From MyTable Group By id) F On F.id = M.id