将TABLE_1的SQL透视查询改造适配至含dt_emission列的TABLE_2
SQL查询适配TABLE_2修改方案
核心修改逻辑
- 所有原查询中引用
TABLE_1的地方统一替换为TABLE_2 - 原
year_dt_emission字段全部替换为YEAR(dt_emission),从日期字段提取年份 - 原
month_dt_emission字段全部替换为MONTH(dt_emission),从日期字段提取月份 YEAR/MONTH函数在SQL Server中本身支持对YYYY-MM-DD格式的日期字段直接运算,之前运行失败大概率是没有同步替换分组、关联条件中的时间字段,不是函数本身的问题。
适配后的完整查询代码
select brand_name , year_dt_emission , month_dt_emission as month_order , case month_dt_emission when 1 then 'Jan'when 2 then 'Feb'when 3 then 'Mar'when 4 then 'Apr'when 5 then 'May'when 6 then 'Jun' when 7 then 'Jul'when 8 then 'Aug'when 9 then 'Set'when 10 then 'Oct'when 11 then 'Nov'when 12 then 'Dec' end as month_dt_emission , [1] as 'Jan', [2] as 'Feb', [3] as 'Mar', [4] as 'Apr', [5] as 'May', [6] as 'Jun' , [7] as 'Jul', [8] as 'Aug', [9] as 'Set', [10] as 'Oct', [11] as 'Nov', [12] as 'Dec' from ( select c.brand_name , j_month.Joining_month , c.month_dt_emission , c.year_dt_emission , count (distinct c.invoice_number) customer_id from ( -- 提前从TABLE_2提取年月,避免后续重复写计算逻辑 select *, YEAR(dt_emission) year_dt_emission, MONTH(dt_emission) month_dt_emission from TABLE_2 ) c left join ( select YEAR(dt_emission) year_dt_emission, brand_name, customer_id, min(MONTH(dt_emission)) Joining_month from TABLE_2 where 1=1 group by YEAR(dt_emission), brand_name, customer_id) j_month on (c.customer_id = j_month.customer_id and c.brand_name = j_month.brand_name and c.year_dt_emission = j_month.year_dt_emission) left join ( select YEAR(dt_emission) year_dt_emission, brand_name, customer_id, count(distinct MONTH(dt_emission)) Months_Active from TABLE_2 where 1=1 group by YEAR(dt_emission), brand_name, customer_id) m_month on (c.customer_id = m_month.customer_id and c.brand_name = m_month.brand_name and c.year_dt_emission = m_month.year_dt_emission) where 1=1 and (m_month.Months_Active > 0 or j_month.Joining_month > 0) group by c.brand_name , j_month.Joining_month , c.month_dt_emission , c.year_dt_emission ) a PIVOT ( sum(customer_id) FOR Joining_month IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10],[11],[12]) ) AS tbpivot
内容的提问来源于stack exchange,提问作者AuReMarks
相关产品推荐
相关产品推荐

