如何计算订单数量和相同订单ID的退货数量?

时间:2019-06-25 13:15:37

标签: sql

我正在尝试从具有列CustomerIDOrderIDReturnFlag的表中派生一个表,作为CustomerID,OrderCount和ReturnCount

我尝试了以下代码,该代码为我提供了2个不同的表,但是我希望结果在单个输出表中。

select "CustomerID", count(DISTINCT "OrderID") as OrderCount  
from "Customer" 
group by "CustomerID";

select "CustomerID", count(DISTINCT "OrderID") as ReturnCount 
from "Customer" 
where "ReturnFlag" = 1 
group by "CustomerID";

源表-

|CustomerID| |OrderID| |ReturnFlag|
|1     | |  A    | |    0 |
|2     | |   B   | |        1 |
|1     | |  C    | |    0 |
|2     | |   D   | |    0 |
|3     | |   E   | |    1 |

预期输出表-

|CustomerID| |OrderCount| |ReturnCount|
|1     | |  2      | |  0     |
|2     | |  2      | |        1  |
|3     | |  1      | |  1     |

3 个答案:

答案 0 :(得分:1)

使用条件聚合:

for(let key in Object.keys(objResult)) {
    console.log(objResult[key]);
}

我有点困惑为什么select "CustomerID", count(DISTINCT case when "ReturnFlag" = 1 THEN "OrderID" end) as ReturnCount count(DISTINCT "OrderID") as OrderCount from "Customer" group by "CustomerID"; 在称为CustomerID的表中不是唯一的。我希望此查询在Customer表上运行,而不是在customers表上运行。

答案 1 :(得分:1)

您没有指定DBMS,所以这是ANSI SQL。

您可以为此使用条件聚合:

$(function(){
    var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
           if($(e).css('position')=='absolute')
                return parseInt($(e).css('z-index'))||1 ;
           })
    );
    alert(maxZ);
});

如果您的DBMS不支持标准的select "CustomerID", count(DISTINCT "OrderID") as OrderCount, count(DISTINCT "OrderID") filter (where "ReturnFlag" = 1) as return_count from "Customer" group by "CustomerID"; 子句,则可以使用大小写表达式:

filter()

答案 2 :(得分:0)

使用Orders表达式进行条件聚合

case