select
    *
     ,CASE
          WHEN deli_type = '内部用酒' THEN '内部用酒'
          WHEN bu_code = '0202/0223'
              THEN(CASE WHEN pl_name = '小郎酒' THEN '小郎酒事业部'
                        WHEN pl_name in ('郎牌特曲', '郎牌原浆', '新郎酒') THEN '郎牌特曲事业部'
                        WHEN pl_name in ('青花郎', '老郎酒', '藏品') THEN '青花郎事业部'
              END
              )
          ELSE  bu_name
    END AS report_bu_name  -- 报表事业部
     ,CASE
          WHEN deli_type = '内部用酒' THEN '内部用酒'
          WHEN bu_code = '0202/0223'
              THEN(CASE WHEN pl_name = '小郎酒' THEN '小郎酒川渝大区'
                        WHEN pl_name in ('郎牌特曲', '郎牌原浆', '新郎酒') THEN '郎特四川大区'
                        WHEN pl_name in ('青花郎', '老郎酒', '藏品') THEN '青花郎川渝大区'
              END
              )
          ELSE  region_name
    END AS report_region_name  -- 报表大区
,year(deli_time) AS deli_year
,quarter(deli_time) as deli_quar
,month(deli_time) AS deli_month
,deli_num / pack_base_num AS ship_num -- 发货件数
,d_amt + e_amt + f_amt + fz_amt + q_amt AS total_amt -- 费用合计
,''     AS region_opera_code -- 区域运营商编码
,''     AS region_opera_name -- 区域运营商名称
from dm.v_ag_sal_deliver a
where exists (
    select
    1
from
	dm.dm_bi_user_permisson
where
	bi_user = '${fine_username}'
	and per_model IN ('all','sal')
	and (
			is_all = 1
			OR per_code = a.bu_code
			OR per_code = a.region_code
			OR per_code = a.office_code
			OR per_code = a.city_unit_code
			)
)
-- 产品线
    ${if(len(sPl_name) == 0,"","and pl_name in ('" + sPl_name + "')")}
-- 品项
    ${if(len(sPi_name) == 0,"","and pi_name in ('" + sPi_name + "')")}
-- 产品
    ${if(len(sProd) == 0,"","and product_code in ('" + sProd + "')")}

-- 事业部
    ${if(len(sBu) == 0,"","and bu_code in ('" + sBu + "')")}
-- 大区
    ${if(len(sRegion) == 0,"","and region_code in ('" + sRegion + "')")}
-- 办事处
    ${if(len(sOffice) == 0,"","and office_code in ('" + sOffice + "')")}
-- 城市单元
    ${if(len(sCu) == 0,"","and city_unit_code in ('" + sCu + "')")}
-- 子主经销商筛选
    ${if(sSub_main== "主经销商",if(len(sDeal)==0,"","and deal_code in ('" + sDeal + "')"),if(len(sDeal)==0,"","and src_deal_code in ('" +sDeal + "')"))}
-- 订单号/发货单号
    ${if(len(sOrder) == 0,"","and (order_code = '" + sOrder + "' or deli_code = '" + sOrder + "')")}
-- 发货时间
  and deli_time >= date('${sStart_date}')
  and deli_time < date('${sEnd_date}') + INTERVAL '1 days'
