oracle 计数差异未加起来

tvokkenx  于 2023-03-17  发布在  Oracle
关注(0)|答案(1)|浏览(167)

我想计算当天唯一CNTR_NBR的数量

SELECT TO_CHAR(BEGIN_DATE, 'DD-MM-YYYY') "DATE"
        , TRAN_TYPE_DESC
        , MENU_OPTN_NAME
        , REASON_CODE
        , REF_FIELD_3  "RC_REF_1"
        , COUNT (DISTINCT CNTR_NBR) AS LPNS
FROM WMS2018.BAP_PROD_TRKG_TRAN_VIEW
WHERE MENU_OPTN_NAME = 'Receive and Sort DCV'
      AND TRUNC(BEGIN_DATE) = TRUNC(SYSDATE)
GROUP BY BEGIN_DATE
        , TRAN_TYPE_DESC
        , MENU_OPTN_NAME
        , REASON_CODE
        , REF_FIELD_3
    ORDER BY 1
    ;

这是它当前返回的

pdsfdshx

pdsfdshx1#

在Oracle中,DATE是一种二进制数据类型,由7个字节组成,代表世纪、世纪年、月、日、小时、分钟和秒。它总是具有这些组件。
有些用户界面选择了默认值,即不显示DATE s的时间部分,而SQL Developer恰好就是这样。您可以在首选项中或使用以下命令更改日期格式:

ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';

然后您将看到每个组中的完整日期和时间。
当您使用GROUP BY begin_date时,您要求它分组到精确到一秒(而不是一天);您需要更改它,以便组跨越一整天。
您可以在GROUP BY子句中使用TO_CHARTRUNC来按日期分组:

SELECT TO_CHAR(BEGIN_DATE, 'DD-MM-YYYY') "DATE"
        , TRAN_TYPE_DESC
        , MENU_OPTN_NAME
        , REASON_CODE
        , REF_FIELD_3  "RC_REF_1"
        , COUNT (DISTINCT CNTR_NBR) AS LPNS
FROM   WMS2018.BAP_PROD_TRKG_TRAN_VIEW
WHERE  MENU_OPTN_NAME = 'Receive and Sort DCV'
AND    BEGIN_DATE >= TRUNC(SYSDATE)
AND    BEGIN_DATE <  TRUNC(SYSDATE) + INTERVAL '1' DAY
GROUP BY TO_CHAR(BEGIN_DATE, 'DD-MM-YYYY')
        , TRAN_TYPE_DESC
        , MENU_OPTN_NAME
        , REASON_CODE
        , REF_FIELD_3
ORDER BY 1;

或:

SELECT TO_CHAR(TRUNC(BEGIN_DATE), 'DD-MM-YYYY') "DATE"
        , TRAN_TYPE_DESC
        , MENU_OPTN_NAME
        , REASON_CODE
        , REF_FIELD_3  "RC_REF_1"
        , COUNT (DISTINCT CNTR_NBR) AS LPNS
FROM   WMS2018.BAP_PROD_TRKG_TRAN_VIEW
WHERE  MENU_OPTN_NAME = 'Receive and Sort DCV'
AND    BEGIN_DATE >= TRUNC(SYSDATE)
AND    BEGIN_DATE <  TRUNC(SYSDATE) + INTERVAL '1' DAY
GROUP BY TRUNC(BEGIN_DATE)
        , TRAN_TYPE_DESC
        , MENU_OPTN_NAME
        , REASON_CODE
        , REF_FIELD_3
ORDER BY TRUNC(BEGIN_DATE);

相关问题