我正在查看包含订单信息的数据库。我正在尝试确定从订购到装运时间超过14天的订单百分比。我很难创建每月%的列。现在我有
Select ol.orderid, ol.productid, Month(ol.shipdate) as monthShipped,
Year(ol.shipdate)as yearShipped,
(Select Count(*) From orderline ol Where datediff(ol.shipdate,o.orderdate)> 14 Group By Month(ol.shipdate), Year(ol.shipdate))/Count(*) as percentage
From orderline ol
Join orders o
on ol.orderid = o.orderid
Group By monthShipped, yearShipped
Order By yearShipped, monthShipped
我收到错误,说我的子查询返回多行。我不想要多行?如果我在子查询中删除了Group By,那么我得到了值,但它没有接近正确。
答案 0 :(得分:0)
第一个问题是shipdate
适用于每个订单行。我假设您的意思是每个订单的最新发货日期。以下内容在订单级别获取此信息:
Select ol.orderid, max(ol.shipdate) as lastshipdate
From orderline ol
Group By ol.orderid;
要获得差异,您需要订单:
Select ol.orderid, datediff(o.orderdate, max(ol.shipdate) ) as diff
From orders o join
orderline ol
on o.orderid = ol.orderid
Group By ol.orderid;
最后,按月获得数字和百分比:
select year(orderdate), month(orderdate),
count(*) as numorders, sum(diff > 14) as numdelayed, avg(diff > 14) as p_dealyed
from (Select ol.orderid, datediff(o.orderdate, max(ol.shipdate) ) as diff, o.orderdate
From orders o join
orderline ol
on o.orderid = ol.orderid
Group By ol.orderid
) o
group by year(orderdate), month(orderdate)
order by 1, 2;
答案 1 :(得分:0)
第一个查询返回按订单发货后14天内发货的订单项次数的百分比。
select monthShipped, yearShipped,
(sum(greater_than_14)/count(*)) percent_exceeding_14
from (
select
month(ol.shipdate) as monthShipped,
year(ol.shipdate) as yearShipped,
(datediff(ol.shipdate,o.orderdate) > 14) greater_than_14
from orderline ol
join orders o on ol.orderid = o.orderid
) t1 group by monthShipped, yearShipped
第二个查询返回订单百分比,其中至少有一个订单行项目在按订购月份分组后的14天内发货超过14天。
select monthOrdered, yearOrdered,
(count(g14)/count(*)) percent_exceeding_14
from (
select
month(orderdate) monthOrdered,
year(orderdate) yearOrdered,
greater_than_14.orderid g14
from orders o left join (
select orderid
from orders o2
where exists (
select 1 from orderline ol
where ol.orderid = o2.orderid
and datediff(ol.shipdate,o2.orderdate) > 14
)
) greater_than_14 on greater_than_14.orderid = o.orderid
) t1 group by monthOrdered, yearOrdered