计算聚合函数中的不同值

时间:2019-04-09 14:14:32

标签: sql

我有一张商店,订单,物品,订购数量和装运数量的表。我想按存储的唯一订单数创建一个摘要,其中发货数量少于订单中一个或多个项目的订购数量。例如:

Store   OrderID ItemID  Ordered Shipped  
A          1      1        5      5  
A          1      2        2      0  
A          2      5        6      4  
A          2      2        4      4  
B          1      6        2      2  
B          1      12       1      1  
B          1      18       4      4  
B          2      8        2      2  
B          3      15       4      3  

我想要以下结果:

Store   Orders  Good    Shorted  
A          2      0        2  
B          3      2        1  

这表明商店A有2个订单,两个订单均未完全履行,而商店B有3个订单,其中2个订单已履行,还有1个未履行。

我正在寻找一种无需使用大量昂贵的子查询即可完成此操作的方法。有什么建议吗?

3 个答案:

答案 0 :(得分:3)

您可以使用视图或子查询来完成。这是我的观点解决方案:

Create view eachOrder as 
  select store, OrderID, sum(Ordered) as O, sum(Shipped) as s 
  from test 
  group by store, OrderID;

select store, 
    count(distinct orderid) as orders, 
    sum(case when o <= s then 1 else 0 end) as good,
    sum(case when o > s then 1 else 0 end) as shorted  
  from eachOrder 
  group by store;

这是我作为子查询的解决方案:

select
  store,
  count(distinct orderid) as orders,
  sum(case when o <= s then 1 else 0 end) as good,
  sum(case when o > s then 1 else 0 end) as shorted 
  from (select store, OrderID, 
          sum(Ordered) as O, 
          sum(Shipped) as s 
        from test 
        group by store, OrderID
      ) as EachOrder
  group by store;

您可以看到两种解决方案here https://paiza.io/projects/_0nkAIwfT2mzYKoehol0KA?language=mysql

答案 1 :(得分:0)

使用子查询

    select t.Store,t.Orders,good,shorted from
(select  Store,count(*) as Orders
     from
     (select distinct Store,OrderID
    from table
     ) a group  by Store
) t
     join
     ( select store,
sum(case when ordered < shipped then 1  else 0 end) as good,
  sum(case when ordered > shipped then 1 else 0 end) as shorted 
from my_table group by store
     ) b on t.store=b.store

答案 2 :(得分:0)

只需计算一个案例:

SELECT
  store,
  Count(DISTINCT orderid) AS orders,
  Sum(DISTINCT CASE WHEN ordered <= shipped THEN orderid END) AS good,
  Sum(DISTINCT CASE WHEN ordered > shipped THEN orderid END) AS shorted 
FROM my_table
GROUP BY store

或将三个不同的计数减少为两个:

SELECT store, orders, good, orders - good AS shorted
FROM
 (
   SELECT
     store,
     Count(DISTINCT orderid) AS orders,
     Sum(DISTINCT CASE WHEN ordered <= shipped THEN orderid END) AS good
   FROM my_table
   GROUP BY store
 ) AS dt