Sample Data Set and Desired Query Result
我有一份零售店åå•ï¼Œè¿™äº›é›¶å”®åº—éšç€æ—¶é—´çš„推移已ç»æ”¹å˜äº†æ‰€æœ‰æƒï¼ˆä»Žå…¬å¸æ‰€æœ‰ï¼Œåˆ°è®¸å¯æˆ–特许ç»è¥ï¼Œå†åˆ°å…¬å¸æ‰€æœ‰ï¼‰ã€‚我æ£åœ¨å°è¯•è·Ÿè¸ªæ¯ä¸ªæ‰€æœ‰æƒç±»åž‹ä¸‹æ¯ä¸ªæœˆå¼€è®¾çš„商店数é‡ã€‚对于所有æƒçš„æ¯æ¬¡æ›´æ”¹ï¼Œæˆ‘在数æ®é›†ä¸éƒ½æœ‰ä¸€ä¸ªæ–°çš„行项目,æ¯ä¸ªè¡Œé¡¹ç›®éƒ½æœ‰ç›¸åº”的更改开始日期和结æŸæ—¥æœŸã€‚
我æ£åœ¨å°è¯•æŒ‰ç…§æ¯ä¸ªæœˆçš„æ•°æ®æŒ‰ç…§æ‰€æœ‰æƒç±»åž‹è®¡ç®—商店​​数é‡ï¼Œè€Œä¸”æˆ‘æ— æ³•ç¡®å®šå¦‚ä½•è®¡ç®—æ‰€æœ‰æœˆä»½çš„å•†åº—åœ¨æ‰€æœ‰æƒå¼€å§‹æ—¥æœŸå’Œç»“æŸæ—¥æœŸä¹‹é—´çš„æ•°é‡ã€‚å¸Œæœ›è¿™å¼ ç…§ç‰‡æ¸…æ¥šåœ°è¡¨æ˜Žäº†æˆ‘çš„ç›®æ ‡ã€‚
select
b.fscl_yr_num
,b.fscl_per_in_yr_num
,a.ownr_type_cd
,sum(case when a.line_start_dt < b.end_dt and a.line_end_dt <= b.End_Dt then 1 else 0 end)
from
(
(
select *
from
(select
store_num
,ownr_type_cd
,case when store_term_dt is not null then 'Closed' else 'Open' end as Status
,case when to_date(trim(store_open_dt),'DD-MON-YY') > to_date(trim(eff_from_dt),'DD-MON-YY') then to_date(trim(store_open_dt),'DD-MON-YY') else to_date(trim(eff_from_dt),'DD-MON-YY') end as Line_Start_Dt
,case when store_term_dt is null then eff_to_dt
when to_date(trim(store_term_dt),'DD-MON-YY') < to_date(trim(eff_to_dt),'DD-MON-YY') then to_date(trim(store_term_dt),'DD-MON-YY') else to_date(trim(eff_to_dt),'DD-MON-YY') end as Line_End_Dt
from
(select
store_num
,store_open_dt
,store_term_dt
,eff_from_dt
,eff_to_dt
,ownr_type_cd
from
appca.d_store_vers
where
upper(cntry_cd_2_dgt_iso) = 'GB'
and postal_cd not like ('BT%')
and store_open_dt is not null
group by
store_num
,store_open_dt
,store_term_dt
,eff_from_dt
,eff_to_dt
,ownr_type_cd
order by
store_num
,eff_from_dt)
group by
store_num
,ownr_type_cd
,case when store_term_dt is not null then 'Closed' else 'Open' end
,case when to_date(trim(store_open_dt),'DD-MON-YY') > to_date(trim(eff_from_dt),'DD-MON-YY') then to_date(trim(store_open_dt),'DD-MON-YY') else to_date(trim(eff_from_dt),'DD-MON-YY') end
,case when store_term_dt is null then eff_to_dt
when to_date(trim(store_term_dt),'DD-MON-YY') < to_date(trim(eff_to_dt),'DD-MON-YY') then to_date(trim(store_term_dt),'DD-MON-YY') else to_date(trim(eff_to_dt),'DD-MON-YY') end
order by
1 asc
,2 asc
,3 asc)
where
to_date(trim(line_start_dt),'DD-MON-YY') < to_date(trim(line_end_dt),'DD-MON-YY')
) A
right join
--Calendar Table--
(
select
fscl_yr_num, fscl_per_in_yr_num, Cal_dt min(to_date(trim(cal_dt),'DD-MON-YY')) as Start_Dt, max(to_date(trim(cal_dt),'DD-MON-YY')) as End_Dt
from
appca.d_cal
where
fscl_yr_num is between 1990 and 2018
group by
fscl_yr_num, fscl_per_in_yr_num
order by
1 asc, 2 asc
) B
on A.line_end_dt = B.cal_dt
)
group by
b.fscl_yr_num
,b.fscl_per_in_yr_num
,a.ownr_type_cd
order by
b.fscl_yr_num
,b.fscl_per_in_yr_num
;
ç”案 0 :(得分:0)
试试这个案例:
sum(case when createTime >(cast(year(createTime) as varchar) +'-'+cast( MONTH(createTime) as varchar)+'-1') and createTime <(cast(year(createTime) as varchar) +'-'+cast( MONTH(createTime) as varchar)+'-31')
then 1 else 0 end) 'Company'