我想返回一个财务年度客户的平均订单价值(订单中所有订单项的Qty * Price
的总和,然后是平均订单总数),表格如下所示
财政年度从1月/ 7月开始(可以作为参数动态传递) 财政年度结束30日/ 6月/年(可作为参数动态传递) UserID(可以作为参数动态传递)
Orders Table
-OrderID
-UserID
-OrderDate
OrderItems Table
-OrderItemID
-OrderID
-Qty
-Price
我使用的脚本语言是coldfusion,db是MSSQL
谢谢大家的时间
CHRIS
答案 0 :(得分:2)
不熟悉coldfusion。
SQL是
SELECT o.UserID, AVG(oi.OrderTotal) AverageOrderValue
FROM Orders o
INNER JOIN
(SELECT OrderID, SUM(Qty*Price) OrderTotal
FROM OrderItems
GROUP BY OrderID) oi ON o.OrderID=oi.OrderID
WHERE o.OrderDate BETWEEN @StartDate AND @EndDate
答案 1 :(得分:1)
declare
@first_param datetime='01-01-2001'
@last_param datetime='01-07-2014'
begin
select AVG(orderid_cnt),sum_qty,a.user_id from (
select sum(b.qty*b.price) as sum_qty,orderid,COUNT(orderid) as orderid_cnt
From orders a
inner join orderitems b
on a.orderid=b.orderid
group by orderid ) a
inner join orders a1
on a.orderid=a1.orderid