【问题标题】:sql query for counting the records of particular id and show in columnsql query for counting the records of particular id and show in column
【发布时间】:2022-12-01 21:22:40
【问题描述】:

I have a following table:-

declare @tab table(name varchar(10),id int)

insert into @tab values ('A',1),('B',1),('C',1),('D',1),('E',2),('F',2)

I need following output:-

declare @tab1 table(name varchar(10),id int, cnt int)

insert into @tab1 values ('A',1,4),('B',1,4),('C',1,4),('D',1,4),('E',2,2),('F',2,2)
select * from @tab1

I tried following query:-

select name,id,count(*) as cnt
from @tab 
group by name,id

Thanks

【问题讨论】:

  • Remove sql-server-2012 tag, because it's no longer supported. Also, very unclear question. What do you want, what do you get with the code you've tried? Please, edit

标签: sql sql-server sql-server-2012


【解决方案1】:

Done

;with a as
(
select Id,name, count(*) over (partition by id) cnt

from @tab
)
select Id,name,cnt
from a

【讨论】:

    【解决方案2】:

    Try this

    select name
         , id
         , count(*) over(partition by id) as cnt
    from @tab
    ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-27
      • 2020-01-19
      • 2022-12-28
      • 2022-12-02
      • 1970-01-01
      • 2021-12-30
      • 2022-12-02
      • 2022-12-02
      相关资源
      最近更新 更多