Sql-Server

在 SQL Server 2012+ 中使用 Partition By 時如何檢測分組變化並根據同一 SQL 語句中的變化執行邏輯?

  • September 23, 2021

如果我有一個包含類似內容的 SQL 語句,

ROW_NUMBER() OVER(PARTITION BY school_area ORDER BY school_area)

我得到:

1 someschool1 schoolarea1
2 someschool2 schoolarea1
3 someschool3 schoolarea1
1 soomschool4 schoolarea2
2 ...

如何檢測該數據分區何時“重置”?換句話說,當我的結果集從上面的 3 變回 1 時,是否可以在同一個 SQL 語句中說明​​這一點?

當我使用時,

CASE 
   WHEN school_area=1 THEN do something
END

我無法執行任何邏輯,例如在 THEN 之後執行電子郵件常式。它不起作用,因為那不是它的用途。我想我會在 WHILE 中完成,但我不知道我是否遺漏了一些我可以在 SQL 語句本身中做的事情。我試圖避免循環和/或游標,但我認為這是唯一的方法。

這是一個 SQL 查詢範例,可以實現您的期望:

create table #school (school_name varchar(20), school_area varchar(20));

insert into #school values ('someschool1', 'schoolarea1'),
('someschool2', 'schoolarea1'),
('someschool3', 'schoolarea1'),
('soomschool4', 'schoolarea2'),
('soomschool5','schoolarea2')

select ROW_NUMBER()  OVER(PARTITION BY school_area ORDER BY school_area), school_name, school_area from #school

-- Get all the school area
select distinct school_area into #school_area from #school;

-- loop into the previously created temp table and collect the required information
declare @area varchar(20);
while (select count(1) from #school_area) >0 
   begin
       select top 1 @area = school_area from #school_area;
       -- do the SQL query you need to extract the data you want for each area (no more "over" clause here)
       select * from #school where school_area = @area;
       --exec msdb..sp_send_dbmail ....(send the result of your previous query by email (for that area)
       delete from #school_area where school_area = @area;
   end


drop table #school;
drop table #school_area;

這是一個範例,您可以在任何 SQL 實例上執行以“查看”行為。如果您想接收電子郵件,請確保您正確參數化 sp_send_dbmail

引用自:https://dba.stackexchange.com/questions/300054