我的查询返回包含客户名和姓的2列的SUM。
返回约40000条记录。我的疑问是: -
SELECT SUM(Orders.BusinessVolumeTotal) AS BV,
SUM(Orders.CommissionableVolumeTotal) AS PV,
ISNULL(Customers.FirstName,''), Customers.LastName
FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND Orders.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
GROUP BY Customers.FirstName, Customers.LastName
但我只想在BV和PV coluymns中返回10行值最高的行。
提前致谢。
答案 0 :(得分:2)
如果您希望每组有10个最高行,则可以在ROW_NUMBER
中使用CTE
:
WITH CTE AS
(
SELECT SUM(Orders.BusinessVolumeTotal) OVER(PARTITION BY Customers.FirstName, Customers.LastName) AS BV,
SUM(Orders.CommissionableVolumeTotal) OVER(PARTITION BY Customers.FirstName, Customers.LastName) AS PV,
ISNULL(Customers.FirstName,'') As FirstName,
Customers.LastName,
RN = ROW_NUMBER()
OVER(PARTITION BY Customers.FirstName, Customers.LastName
ORDER BY (Orders.BusinessVolumeTotal + Orders.CommissionableVolumeTotal) DESC)
FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND Orders.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
)
SELECT * FROM CTE WHERE RN <= 10
答案 1 :(得分:1)
根据两列的组,您可以获得如下所示的前10行:
SELECT TOP 10
SUM(Orders.BusinessVolumeTotal) AS BV,
SUM(Orders.CommissionableVolumeTotal) AS PV,
ISNULL(Customers.FirstName,''), Customers.LastName
FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND Orders.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
GROUP BY Customers.FirstName, Customers.LastName
ORDER BY SUM(Orders.BusinessVolumeTotal) + SUM(Orders.CommissionableVolumeTotal) DESC
答案 2 :(得分:0)
获得BV前10名和PV前10名的一种方法是为每个人写一个查询:
SELECT TOP 10
SUM(Orders.BusinessVolumeTotal) AS BV, SUM(Orders.CommissionableVolumeTotal) AS PV, ISNULL(Customers.FirstName,''), Customers.LastName
FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND Orders.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
GROUP BY Customers.FirstName, Customers.LastName
ORDER BY BV DESC
SELECT TOP 10
SUM(Orders.BusinessVolumeTotal) AS BV, SUM(Orders.CommissionableVolumeTotal) AS PV, ISNULL(Customers.FirstName,''), Customers.LastName
FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND Orders.OrderDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
GROUP BY Customers.FirstName, Customers.LastName
ORDER BY PV DESC