如何获取按id分组的数据

how to get data grouped by ids

我根据 id_card 在临时 table 中对数据进行了分组。每张卡片都有多项活动。我想为该特定卡上发生的所有活动发送 1 封电子邮件。但是,我不知道如何根据id获取数据。我应该使用游标来获取 ID ? table 中的示例,id_card =1 需要 2 行,id_card = 3 需要 2 行,依此类推

id_card   dat_actitity     type 
1         2022-04-21       tag on           
1         2022-04-23       tag off  
2         2022-04-28       tag on
2         2022-04-20       tag off  
2         2022-04-01       tag on
3         2022-04-27       tag on

你能帮忙吗?非常感谢

你可以使用 while 循环,像这样

declare @id int

-- get the first id (minimum)
select @id = min(id) from #tmp

while @id is not null
begin 
   -- get the rows
   select * from #tmp where id = @id

   -- send mail
   exec msdb.dbo.sp_send_dbmail . . .

   -- get next id
   select @id = min(id) from #tmp where id > @id
end

db<>fiddle demo

select @id = min(id_card) from #tmp
while @id is not null
begin 
 drop table if exists  #rows 
   -- get the rows
   select * into #rows from #tmp where id_card = @id
 
   if (@@ROWCOUNT > 0)
   begin 
   -- send mail
 SET @Subject = 'Flagged Card activity noticed on Card with ID ' + convert(varchar(10), @id) 
 SET @Message =
                    N'<H3>Details of the activity are as follows:</H3>' +
                    N'<table border="1">' +
                    N'<tr bgcolor=#ADD6FF>' +                   
                    N'<th>Activity Date</th>' +
                    N'<th>Activity Day</th>' +
                    N'<th>Time</th>' +                  
                    N'<th>Activity Type</th>' +             
                    N'</tr>' +                  
                    CAST(( 
                    SELECT  
                            td = Convert(varchar(10), dat_activity, 103), '',
                            td = FORMAT(dat_activity,'ddd'), '',
                            td = Convert(varchar(8), Convert(time, dat_activity)), '',                                  
                            td = ISNULL(str_activitydesc,'N/A')                     
                            
                            FROM #tmp
                            order by dat_activity desc
                            FOR XML PATH('tr'), ELEMENTS) AS NVARCHAR(MAX)) +
                        N'</table>' 
        PRINT 'Email Sent'
        --Now send the email
        EXEC msdb.dbo.sp_send_dbmail
            @profile_name = 'Profile',
            @recipients = @recipientList,
            @subject = @Subject,
            @body = @Message,
            @body_format = 'HTML',
            @importance = 'High'
  end
   -- get next id
   select @id = min(id_card) from #tmp where id_card > @id
end