必须在2002年和2002年的当月找到总销售额和获得的总折扣
表1:SalesOrderDetail
- UnitPrice
- UnitPriceDiscount
- OrderQty
表2:SalesOrderHeader
- OrderDate
附加是这两个表的模式的快照
https://i.stack.imgur.com/f2b5A.png
我可以设法单独得到结果,但不知道如何 组合/聚合它们......是否使用转置或转轴......
#Yearly
select DATE_FORMAT(a.OrderDate,'%Y') AS Yearly,sum(b.UnitPriceDiscount) as DiscTotal,
SUM((`UnitPrice` * OrderQty)-UnitPriceDiscount) AS total
FROM SalesOrderHeader a join SalesOrderDetail b
on b.SalesOrderID = a.SalesOrderID
WHERE YEAR(OrderDate) = 2002
group by Yearly
order by MONTH(OrderDate)
#CurMonthOfYear
select DATE_FORMAT(a.OrderDate,'%M') AS CurrentMonth,sum(b.UnitPriceDiscount) as DiscountAmt,
SUM((`UnitPrice` * OrderQty)-UnitPriceDiscount) AS total
FROM SalesOrderHeader a join SalesOrderDetail b
on b.SalesOrderID = a.SalesOrderID
WHERE month(OrderDate) = MONTH( NOW())
**结果应采用以下格式**
Metrics Yearly CurMonthOfYear
DiscountAmt 540.82 28.48
TotalSales 303.17 237.2
答案 0 :(得分:1)
您的问题建议有条件的汇总。但是,这最简单的分为四列:
select sum(sod.UnitPriceDiscount) as DiscTotal_year,
sum((UnitPrice * OrderQty) - UnitPriceDiscount) AS total_year,
sum(case when month(sod.OrderDate) = month(now())
then sod.UnitPriceDiscount else 0
end) as DiscTotal_month,
sum(case when month(sod.OrderDate) = month(now())
then (UnitPrice * OrderQty) - UnitPriceDiscount else 0
end) as Total_month
from SalesOrderHeader soh join
SalesOrderDetail sod b
on sod.SalesOrderID = soh.SalesOrderID
where year(soh.OrderDate) = 2002 ;
虽然您可以将其转换为单独的行,但这会使查询更复杂。
答案 1 :(得分:1)
select a.Metrics , a.yearly , b.CurMonthOfyear FROM
(
select 'DiscountAmt' as Metrics , sum(b.UnitPriceDiscount) as yearly
FROM SalesOrderHeader a join SalesOrderDetail b
on b.SalesOrderID = a.SalesOrderID
WHERE YEAR(OrderDate) = 2002
union all
select 'TotalSales' as Metrics , SUM((b.UnitPrice * b.OrderQty)-b.UnitPriceDiscount) AS yearly
FROM SalesOrderHeader a join SalesOrderDetail b
on b.SalesOrderID = a.SalesOrderID
WHERE YEAR(OrderDate) = 2002
)a
inner join
(
select 'DiscountAmt' as Metrics , sum(b.UnitPriceDiscount) as CurMonthOfyear
FROM SalesOrderHeader a join SalesOrderDetail b
on b.SalesOrderID = a.SalesOrderID WHERE month(OrderDate) = MONTH( NOW())
union all
select 'TotalSales' as Metrics , SUM((b.UnitPrice * b.OrderQty)-b.UnitPriceDiscount) AS CurMonthOfyear
FROM SalesOrderHeader a join SalesOrderDetail b
on b.SalesOrderID = a.SalesOrderID
WHERE month(OrderDate) = MONTH( NOW())
)
b ON a.Metrics = b.Metrics
这不是数据透视或转置,但查询有助于以所需格式获取输出。