逐行计数按变量计数

时间:2015-02-05 20:03:07

标签: sql oracle oracle-sqldeveloper

我有以下查询 -

SELECT
  P.PRODUCT_NUMBER, 
  P.PRODUCT_DESCRIPTION, 
  SUM(S.NET_AMOUNT), 
  ROUND(STDDEV(S.NET_AMOUNT),2) AS STD_DEV  
--(SELECT COUNT OF NET_AMOUNT < = 1$ FROM PFI_FACT_SALES GROUPED BY THE SAME P.PRODUCT_NUMBER) AS CNT
    FROM PFI_DIM_PRODUCT P
    JOIN PFI_FACT_SALES S
    ON P.PRODUCT_PK_ID = S.PRODUCT_PK_ID
    WHERE P.PRODUCT_NUMBER = 'ABC'
      GROUP BY P.PRODUCT_NUMBER, P.PRODUCT_DESCRIPTION;

这是我无法弄清楚的部分 -

(SELECT COUNT OF NET_AMOUNT < = 1$ FROM PFI_FACT_SALES GROUPED BY THE SAME P.PRODUCT_NUMBER) AS CNT 

按产品编号获取必要行级数据组的最佳方法是什么?产品描述?

感谢。

1 个答案:

答案 0 :(得分:1)

一种方法是使用相关子查询:

SELECT P.PRODUCT_NUMBER, P.PRODUCT_DESCRIPTION, SUM(S.NET_AMOUNT), 
       ROUND(STDDEV(S.NET_AMOUNT), 2) AS STD_DEV  ,
       (SELECT COUNT(*)
        FROM PFI_FACT_SALES s2
        WHERE s2.PRODUCT_PK_ID = s.PRODUCT_PK_ID AND
              NET_AMOUNT <= 1
       ) as CNT
FROM PFI_DIM_PRODUCT P JOIN
     PFI_FACT_SALES S
     ON P.PRODUCT_PK_ID = S.PRODUCT_PK_ID
WHERE P.PRODUCT_NUMBER = 'ABC'
GROUP BY P.PRODUCT_NUMBER, P.PRODUCT_DESCRIPTION;

我很确定你也可以用条件窗口总和来做到这一点:

SELECT P.PRODUCT_NUMBER, P.PRODUCT_DESCRIPTION, SUM(S.NET_AMOUNT), 
       ROUND(STDDEV(S.NET_AMOUNT), 2) AS STD_DEV,
       SUM(CASE WHEN NET_AMOUNT <= 1 THEN 1 ELSE 0 END) OVER (PARTITION BY s.PRODUCT_PK_ID) as CNT
FROM PFI_DIM_PRODUCT P JOIN
     PFI_FACT_SALES S
     ON P.PRODUCT_PK_ID = S.PRODUCT_PK_ID
WHERE P.PRODUCT_NUMBER = 'ABC'
GROUP BY P.PRODUCT_NUMBER, P.PRODUCT_DESCRIPTION;