简体   繁体   中英

Adventure Works SQL Server 2014 Enquiry

I am writing a SQL query using the AdventureWorks 2014 database. I want to show which employee has sold for the highest order value.

I tried to write each select statement by itself (see below), but I'd like to be able to combine both queries into one:

select 
    s.SalesOrderID, s.SalesPersonID, COUNT(sd.SalesOrderID) as count 
from 
    Sales.SalesOrderHeader s, Sales.SalesOrderDetail sd
where 
    s.SalesOrderID = sd.SalesOrderID 
group by           
    sd.SalesOrderID, s.SalesOrderID, s.SalesPersonID 
order by 
    sd.SalesOrderID

select 
    sd.SalesOrderID, sd.LineTotal, count (sd.SalesOrderID) as count 
from 
    Sales.SalesOrderDetail sd
group by 
    sd.SalesOrderID, sd.LineTotal 
order by 
    sd.SalesOrderID

在此处输入图片说明

are you looking for something like this:

select top 1  
    s.SalesPersonID
    ,sum(sd.LineTotal ) as orderTotal
    s.salesorderid
from
    Sales.SalesOrderHeader s
    inner join  Sales.SalesOrderDetail sd
        on s.SalesOrderID = sd.SalesOrerID
group by 
    s.SalesPersonID
    s.salesorderid
order by
    orderTotal desc

in SQL server you can just ask for a limited number of rows with the top function (this can give you the highest order value when sorted correctly). this can be used with a group by that adds all the line totals together that have the same values in the columns being grouped by.

This is what I would do, to get the total by each Sales Person. Order by the Sum(sd.LineTotal) descending to get the Highest Value.

select s.SalesPersonID ,COUNT(sd.SalesOrderID) as count,sum(sd.LineTotal ) as orderTotal  
from Sales.SalesOrderHeader s 
Inner Join Sales.SalesOrderDetail sd ON s.SalesOrderID=sd.SalesOrderID 
group by s.SalesPersonID 
order by 3 Desc

We appreciate your effort. However, there is a simpler way to get your answer.

SELECT 
-- TOP 1   //to get highest order total
 s.SalesPersonID
 ,COUNT(sd.SalesOrderID) as Total_Count
 ,sum(sd.LineTotal) as orderTotal  
FROM 
  Sales.SalesOrderHeader s Inner Join Sales.SalesOrderDetail sd 
  ON s.SalesOrderID=sd.SalesOrderID 
GROUP BY s.SalesPersonID 
HAVING s.SalesPersonID IS NOT NULL
ORDER BY sum(sd.LineTotal) desc

What I am doing is, joining SalesOrderHeader with SalesOrderDetail through SalesOrderId and using aggregate functions to get desired result.

Order by is use to get highest value first. Top 1 is use to get only desired output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM