如果在 Oracle SQL 中进行累积计数
Doing a Cumulative Count if in Oracle SQL
请参阅附件以供参考。假设我有一个 Table CARRIER_RESPONSE
,具有以下字段 Carrier
、Shipment
、Acceptance
、Day
我想获得每个承运人每天的累计接受计数。
至此我得到了下面的代码:
SELECT Carrier
,Shipment
,Acceptance
,Day
,ROW_NUMBER() OVER (
PARTITION BY Carrier
, Day
, Acceptance
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE
此代码为接受响应 = A 的行提供了正确的 运行 计数,但在接受响应 = D 的行上,我还想显示接受响应 = A 的 运行 计数.
基本上每一行我都想指出今天承运人接受了多少次装运。这可能吗?
谢谢,
阿米尔
运营商响应:
一种方法 - 使用带有分析子句和窗口的求和。
SELECT Carrier
,Shipment
,Acceptance
,Day
,sum(Case when Acceptance is not null then 1 else 0 end) OVER (
PARTITION BY Carrier
, Day
ORDER BY Day
ROWS between unbounded preceding and current row
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE
重新阅读后,您似乎需要计算 A 和 D
SELECT Carrier
,Shipment
,Acceptance
,Day
,sum(Case when Acceptance='A' then 1 else 0 end) OVER (
PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day",
sum(Case when Acceptance='D' then 1 else 0 end) OVER (
PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count for Deny per Day"
FROM CARRIER_RESPONSE
我想你想要:
SELECT Carrier, Shipment, Acceptance, Day,
SUM(CASE WHEN Acceptance = 'A' THEN 1 ELSE 0 END) OVER
(PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE;
如果Acceptance
只取值'A'
和NULL
,那么你可以将其缩短为:
SELECT Carrier, Shipment, Acceptance, Day,
COUNT(Acceptance) OVER
(PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE;
请参阅附件以供参考。假设我有一个 Table CARRIER_RESPONSE
,具有以下字段 Carrier
、Shipment
、Acceptance
、Day
我想获得每个承运人每天的累计接受计数。
至此我得到了下面的代码:
SELECT Carrier
,Shipment
,Acceptance
,Day
,ROW_NUMBER() OVER (
PARTITION BY Carrier
, Day
, Acceptance
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE
此代码为接受响应 = A 的行提供了正确的 运行 计数,但在接受响应 = D 的行上,我还想显示接受响应 = A 的 运行 计数.
基本上每一行我都想指出今天承运人接受了多少次装运。这可能吗?
谢谢,
阿米尔
运营商响应:
一种方法 - 使用带有分析子句和窗口的求和。
SELECT Carrier
,Shipment
,Acceptance
,Day
,sum(Case when Acceptance is not null then 1 else 0 end) OVER (
PARTITION BY Carrier
, Day
ORDER BY Day
ROWS between unbounded preceding and current row
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE
重新阅读后,您似乎需要计算 A 和 D
SELECT Carrier
,Shipment
,Acceptance
,Day
,sum(Case when Acceptance='A' then 1 else 0 end) OVER (
PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day",
sum(Case when Acceptance='D' then 1 else 0 end) OVER (
PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count for Deny per Day"
FROM CARRIER_RESPONSE
我想你想要:
SELECT Carrier, Shipment, Acceptance, Day,
SUM(CASE WHEN Acceptance = 'A' THEN 1 ELSE 0 END) OVER
(PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE;
如果Acceptance
只取值'A'
和NULL
,那么你可以将其缩短为:
SELECT Carrier, Shipment, Acceptance, Day,
COUNT(Acceptance) OVER
(PARTITION BY Carrier
ORDER BY Day
) AS "Cumulative Count of Acceptance per Day"
FROM CARRIER_RESPONSE;