如何从SQL Server中的其他表传递值

时间:2018-10-20 02:27:04

标签: sql-server

我想计算每个产品和产品子类别的销售和回报百分比。

WITH F1 (PROD_CAT, PROD_SUB_CAT, TOTAL_SALES) AS 
(
    SELECT 
        PRODUCT_CAT_CODE,
        PRODUCT_SUBCAT_CODE,
        SUM(TOTAL_AMT)
    FROM
        TRANSACTION_INFO
    WHERE 
        TOTAL_AMT > 0
    GROUP BY 
        PRODUCT_CAT_CODE, PRODUCT_SUBCAT_CODE
), F2 (PROD_CAT, PROD_SUB_CAT, TOTAL_RETURNS) AS 
(
    SELECT 
        PRODUCT_CAT_CODE,
        PRODUCT_SUBCAT_CODE,
        SUM(TOTAL_AMT)
    FROM
        TRANSACTION_INFO
    WHERE 
        TOTAL_AMT < 0
    GROUP BY 
        PRODUCT_CAT_CODE, PRODUCT_SUBCAT_CODE
)
SELECT 
    T1.PRODUCT_CAT_CODE,
    T1.PRODUCT_SUBCAT_CODE,
    F1.TOTAL_SALES,
    F1.TOTAL_SALES * 100 / (SELECT SUM(TOTAL_AMT)
                            FROM TRANSACTION_INFO) AS [%AGE TOTAL SALES],
    F2.TOTAL_RETURNS, 
    F2.TOTAL_RETURNS * 100 / (SELECT SUM(TOTAL_AMT)
                              FROM TRANSACTION_INFO) AS [%AGE TOTAL_RETURNS]
FROM 
    TRANSACTION_INFO T1
INNER JOIN 
    F1 ON T1.PRODUCT_CAT_CODE = F1.PROD_CAT
INNER JOIN 
    F2 ON T1.PRODUCT_CAT_CODE = F2.PROD_CAT
WHERE 
    T1.PRODUCT_CAT_CODE = F1.PROD_CAT
    AND T1.PRODUCT_CAT_CODE = F2.PROD_CAT
GROUP BY 
    T1.PRODUCT_CAT_CODE,
    T1.PRODUCT_SUBCAT_CODE,
    F1.TOTAL_SALES,
    F2.TOTAL_RETURNS

这将返回467条记录,而我只有23条产品记录。

请提出解决此问题的任何方法...

2 个答案:

答案 0 :(得分:0)

您需要同时加入 PRODUCT_CAT_CODE PRODUCT_SUBCAT_CODE

SELECT
    ...
FROM TRANSACTION_INFO T1
INNER JOIN F1 ON T1.PRODUCT_CAT_CODE = F1.PROD_CAT
    AND T1.PRODUCT_SUBCAT_CODE = F1.PRODUCT_SUBCAT_CODE
INNER JOIN F2 ON T1.PRODUCT_CAT_CODE = F2.PROD_CAT
    AND T1.PRODUCT_SUBCAT_CODE = F2.PRODUCT_SUBCAT_CODE
WHERE ...

答案 1 :(得分:0)

我认为,在加入Transaction_info时,您还应该考虑如下所述的product_sub_cat:

FROM TRANSACTION_INFO T1
INNER JOIN F1 ON T1.PRODUCT_CAT_CODE = F1.PROD_CAT AND T1.PRODUCT_SUBCAT_CODE = F1.PRODUCT_SUBCAT_CODE
INNER JOIN F2 ON T1.PRODUCT_CAT_CODE = F2.PROD_CAT AND T2.PRODUCT_SUBCAT_CODE = F1.PRODUCT_SUBCAT_CODE

&似乎没有使用where子句。