-- ======================================
--  1_report_新零售订单明细
-- ======================================

SELECT
    T3.organ_code AS organ_code
    ,T3.organ_name AS organ_name
    ,T3.comm_id     AS comm_id
    ,T3.comm_name   AS comm_name
    ,T2.categoryLevel1 AS categoryLevel1-- 品类名称
    ,T2.goodsTitle     AS goodsTitle -- 商品名称
    ,substr(T1.createTime,1,10)     AS createTime -- 创建时间
    ,COUNT(T1.orderNo) AS orderNum  -- 订单数量
    ,SUM(IFNULL(T1.salePrice,0)) - SUM(IFNULL(T1.refundCash,0)) AS AMOUNT-- 金额
    ,ROW_NUMBER() over (ORDER BY COUNT(T1.orderNo)) AS RK
FROM
(
    SELECT
    orderNo  -- 订单号
    ,vid
    ,vidName -- 项目名称
    ,salePrice -- 销售价格
    ,refundCash -- 退款金额
    ,createTime -- 创建时间
    FROM dw.dwd_innoveco_order_info_d -- 订单信息
    WHERE 1=1
    ${IF(LEN(p_startdate)>0,"AND createTime LIKE '"+FORMAT(p_startdate,"yyyy-MM")+"%'","")}

)T1
LEFT JOIN
(
    SELECT
    categoryLevel1  -- 品类名称
    ,skuNum         -- 商品数量
    ,orderNo        -- 订单号
    ,goodsTitle     -- 商品名称
    FROM dw.dwd_innoveco_order_item_d -- 订单项信息
)T2
ON T1.orderNo = T2.orderNo
RIGHT JOIN
(
    SELECT
 --   DISTINCT
    organ_code
    , organ_name
    , comm_id
    , comm_name
    , weim_comm_id
    FROM dw.dim_organ_mapping
)T3
ON T1.vid = T3.weim_comm_id
WHERE T3.comm_id IS NOT NULL
AND T1.createTime is not null
${IF(LEN(p_cate)>0," AND T2.categoryLevel1 IN ('"+JOINARRAY(p_cate,"','")+"')", "")}
${IF(LEN(p_good)>0," AND T2.goodsTitle IN ('"+JOINARRAY(p_good,"','")+"')", "")}
${IF(LEN(p_area)>0," AND T3.organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
${if(left(fine_role,2)=="项目","and T3.comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
GROUP BY
T3.organ_code
,T3.organ_name
,T3.comm_id
,T3.comm_name
,T2.categoryLevel1
,T2.goodsTitle
,substr(T1.createTime,1,10)
