这只是存储过程的选择部分,但它应该告诉你该怎么做:
declare @products table
(
Name varchar(50),
id int
)
declare @orderitems table
(
id int,
orderid int,
productid int,
orderitemquantity int
)
declare @orders table
(
orderid int,
ordertotal decimal(18,2)
)
insert into @products VALUES ('apple', 1)
insert into @products VALUES ('orange', 2)
insert into @products VALUES ('pear', 3)
insert into @products VALUES ('melon', 4)
insert into @orders values(1, 19.0)
insert into @orders values(2, 25.5)
insert into @orders values(3, 9.5)
insert into @orders values(4, 13.5)
insert into @orders values(5, 8.5)
insert into @orderitems VALUES(1, 1, 1, 20)
insert into @orderitems VALUES(2, 1, 2, 10)
insert into @orderitems VALUES(3, 2, 3, 5)
insert into @orderitems VALUES(4, 2, 4, 4)
insert into @orderitems VALUES(5, 3, 1, 10)
insert into @orderitems VALUES(6, 3, 2, 5)
insert into @orderitems VALUES(7, 4, 3, 3)
insert into @orderitems VALUES(8, 4, 4, 2)
insert into @orderitems VALUES(9, 5, 1, 5)
insert into @orderitems VALUES(10, 5, 4, 2)
;WITH summary as
(
SELECT p.Name as ProductName,
COUNT(o.orderid) as 'Orders Count',
ISNULL(Sum(o.ordertotal),0) AS 'Total Sales Value',
ISNULL(Sum(oi.orderitemquantity),0) AS 'Total Sales Quantity'
FROM @products p
INNER JOIN @orderitems oi on oi.productid = p.id
INNER JOIN @orders o on o.orderid = oi.orderid
GROUP BY p.Name
)
SELECT ProductName, [Orders Count], [Total Sales Value], [Total Sales Quantity],
RANK() OVER (ORDER BY [Total Sales Value] DESC) AS ValueRanking,
RANK() OVER (ORDER BY [Total Sales Quantity] DESC) AS QuantityRanking FROM summary
请注意这里的一些事情。可以将此代码剪切并粘贴到 Management Studio 查询窗口中并照此运行。它从一些表声明和示例数据的插入开始。问一个问题时,如果你做这部分工作总是有用的;如果完成了最无聊的部分,人们更有可能回答!
COUNT() 不需要 ISNULL 保护;如果没有值,则返回 0。
给定最终数据,您会发现 ValueRanking 和 QuantityRankings 是不同的(为了说明这一点,我对数据进行了修改)。这意味着最终结果只能按其中之一排序(或者实际上按任何其他列 - 排序不依赖于排名)。
HTH