我正在使用两个表,一个称为客户,一个称为订单。 客户表中有三个customerType值,“现金”,“企业”和“个人”。 我需要找到每周每种customerType的销售百分比。
这是我到目前为止遇到的麻烦:
select Customer.customerType as 'Customer Type',
format(dateadd(day, -datediff(day, 0, [dbo].[Order].orderDate) % 7, [dbo].[Order].orderDate), 'dd-MM-yy') as 'Week of',
(case
when Customer.customerType = 'Cash' then (select sum([dbo].[Order].totalValue) from [dbo].[Order], Customer
where [dbo].[Order].customerId = Customer.id
and Customer.customerType = 'Cash')
when Customer.customerType = 'Corporate' then (select sum([dbo].[Order].totalValue) from [dbo].[Order], Customer
where [dbo].[Order].customerId = Customer.id
and Customer.customerType = 'Corporate')
else (select sum([dbo].[Order].totalValue) from [dbo].[Order], Customer
where [dbo].[Order].customerId = Customer.id
and Customer.customerType = 'Personal')
end) / sum([dbo].[Order].totalValue) as 'Percentage of Sales for the Week'
from [dbo].[Order], Customer
where Customer.id = [dbo].[Order].customerId
group by format(dateadd(day, -datediff(day, 0, [dbo].[Order].orderDate) % 7, [dbo].[Order].orderDate), 'dd-MM-yy'), Customer.customerType
order by format(dateadd(day, -datediff(day, 0, [dbo].[Order].orderDate) % 7, [dbo].[Order].orderDate), 'dd-MM-yy')
这真是一团糟,我很失落。请帮忙!!!
答案 0 :(得分:-1)
根据您发布的查询,我将其简化为以下内容
注意:
(1)避免使用旧式连接table1, table2
,而应使用INNER JOIN
。 (2)使用表别名
SELECT c.customerType as [Customer Type],
format(dateadd(day, -datediff(day, 0, o.orderDate) % 7, o.orderDate), 'dd-MM-yy') as [Week of],
SUM (o.totalValue)
/ SUM (SUM (o.totalValue) ) OVER (PARTITION BY format(dateadd(day, -datediff(day, 0, o.orderDate) % 7, o.orderDate), 'dd-MM-yy'))
as [Percentage of Sales for the Week]
FROM Customer c
INNER JOIN [dbo].[Order] o on c.id = o.customerId
GROUP BY c.customerType,
format(dateadd(day, -datediff(day, 0, o.orderDate) % 7, o.orderDate), 'dd-MM-yy')
ORDER BY [Week of], c.customerType