所以我似乎无法找到具体的答案
在我们的订购系统中,客户希望获得一份显示产品和每月订购数量的报告
报告列如下所示
项目,1月,2月,3月
每个月下的将是该月订购的总数量
以下是我目前的代码,仅显示1月的订单
SELECT
[Order].Date
, CONVERT(CHAR(12), DATENAME(MONTH, [Order].Date)) as 'Month'
, ISNULL([order].TotalQuantity, [order].UnitQtysQtyPerUnit*[order].Quantity) as 'Quantity'
, [Order].Productname as 'Product'
FROM [Order]
LEFT OUTER JOIN CartTransaction ON CartTransaction.CartTransaction_Id = [Order].CartTransaction_Id
LEFT OUTER JOIN Customer ON Customer.Customer_Id = [Order].Customer_Id
LEFT OUTER JOIN CostCentre ON CostCentre.CostCentre_Id = [Order].CostCentre_Id
where CustomerName = 'Customer A' and [Order].Date between '2017-01-01' and '2017-01-31'
答案 0 :(得分:1)
如果您要生成报告,则应该让报告层处理数据透视,但您可以按month
汇总数据,如下所示:
select
dateadd(month, datediff(month, 0, [Order].Date ), 0) as 'MonthDate'
, convert(char(12),datename(month, [Order].Date)) as 'Month'
, sum(isnull([order].TotalQuantity, [order].UnitQtysQtyPerUnit*[order].Quantity)) as 'Quantity'
, [Order].Productname as 'Product'
from [Order]
left outer join CartTransaction
on CartTransaction.CartTransaction_Id = [Order].CartTransaction_Id
left outer join Customer
on Customer.Customer_Id = [Order].Customer_Id
left outer join CostCentre
on CostCentre.CostCentre_Id = [Order].CostCentre_Id
where CustomerName = 'Customer A'
and [Order].Date between '2017-01-01' and '2017-01-31'
group by
dateadd(month, datediff(month, 0, [Order].Date ), 0)
, convert(char(12),datename(month, [Order].Date))
, [Order].ProductName
order by dateadd(month, datediff(month, 0, [Order].Date ), 0)
答案 1 :(得分:0)
不要假设我们熟悉数据结构,请提供有关该问题的更多信息。
你最可能缺少的是分组。您必须按项目和日期分组,并获得每月totalQuantity的计算TotalSum。
草图:
Select o.ProductName, o.Date, Sum(o.TotalQuantity) as Quantity
From order o, Carttrans ct, customer c, costCent cc
where o.cartTransaction_id = ct.CartTransaction_id
and c.customer_id = o.customer_id
And cs.costcentre_id = o.costcentre_id
And customerName = '...'
and o.Date between ....
Group by o.ProductName and o.Date