在SQL Server中循环结果

时间:2018-10-10 17:53:33

标签: sql sql-server database-cursor

示例表

id  emplrcd effdt   country visited
------------------------------------
112233  0   10/9/2018   US
112233  1   10/10/2018  IND
112233  1   10/11/2018  BAN
112233  1   10/12/2018  PAK
112233  0   10/13/2018  US
112233  2   10/14/2018  IND
112233  2   10/16/2018  THA
112233  2   10/17/2018  SIN
112233  0   10/18/2018  US

223344  0   10/9/2018   US
223344  1   10/10/2018  IND
223344  1   10/11/2018  BAN
223344  1   10/12/2018  PAK
223344  0   10/13/2018  US
223344  2   10/14/2018  IND

我想循环查询的某些结果集,例如id 112233来自美国,位于两个美国国家代码之间,其中国家代码代表他访问过的国家。

count(*)所在国家=美国-> 3

现在,我想遍历我的结果3次,以获取他外出的所有中间日期。可以在单个SQL查询中完成此操作吗?还是需要像游标这样的操作?

上述游标或查询的结果应返回以下行

112233  1   10/10/2018  IND
112233  1   10/11/2018  BAN
112233  1   10/12/2018  PAK
112233  2   10/14/2018  IND
112233  2   10/16/2018  THA
112233  2   10/17/2018  SIN

223344  1   10/10/2018  IND
223344  1   10/11/2018  BAN
223344  1   10/12/2018  PAK

3 个答案:

答案 0 :(得分:2)

我将使用窗口功能:

select t.*
from (select t.*,
             min(case when t.country = 'US' then t.effdt end) over (partition by t.id) as us_min_effdt,
             max(case when t.country = 'US' then t.effdt end) over (partition by t.id) as us_max_effdt
      from t
     ) t
where country <> 'US' and
      effdt >= us_min_effdt and efft < us_max_effdt;

答案 1 :(得分:1)

这是使用CTE设置边界条件的解决方案。

-------------------------
-- TEST SCHEMA

create table #datatable (id varchar(6), emplrcd int, effdt date, [country visited] varchar (3))

insert into #datatable values

('112233',0,'10/9/2018 ','US '),
('112233',1,'10/10/2018','IND'),
('112233',1,'10/11/2018','BAN'),
('112233',1,'10/12/2018','PAK'),
('112233',0,'10/13/2018','US '),
('112233',2,'10/14/2018','IND'),
('112233',2,'10/16/2018','THA'),
('112233',2,'10/17/2018','SIN'),
('112233',0,'10/18/2018','US '),
('223344',0,'10/9/2018 ','US '),
('223344',1,'10/10/2018','IND'),
('223344',1,'10/11/2018','BAN'),
('223344',1,'10/12/2018','PAK'),
('223344',0,'10/13/2018','US '),
('223344',2,'10/14/2018','IND')

-------------------------
-- QUERY

; WITH boundryDate AS 
(
    SELECT 
        id
         ,min (effdt) mindate
         , max(effdt) maxdate

     FROM
        #datatable
     WHERE
        [country visited] = 'US'
     GROUP BY
        id
)

SELECT
    *
FROM
    #datatable dt

    JOIN boundryDate bd
        on dt.id = bd.id
        and dt.effdt between bd.mindate and bd.maxdate
WHERE
    [country visited] <> 'US'

答案 2 :(得分:-1)

使用EXISTS()函数返回所有非“ US”行,其中EXISTS()之前为“ US”行,EXISTS()之后为“ US”行。