简体   繁体   中英

How do I select max date for each row from a subquery

Let's say I want to select the 3 bestsellers in a supermarket. To do this, I have to add each sale to get the total for each product:

SELECT TOP(3) *
FROM
(
   SELECT
   SUM(s.individual_sale) AS totalsales,
   p.productID AS ID,
   p.productName AS Name

   FROM
   sales s,
   products p

   WHERE
   1=1
   AND p.productID = s.productID

   GROUP BY
   p.productID,
   p.productName
   ) AS top_sellers

ORDER BY
top_sellers.totalsales DESC

It then returns me something like this:

ID..|.Name.|.totalsales

55.|.milk....|.1000

24.|.candy.|.800

67.|.juice...|.500

Now I want to retrieve a 4th column containing the last sale from each of these items, like querying "MAX saledate" to each one. How do I accomplish that?

EDIT: Adding MAX(s.saledate) isn't helping. It retrieves a date like 01 Jan 2012 to all rows, but if I query MAX(s.saledate) individually for each entry of the table above, it returns the correct date... My question is, how can I add the column MAX(s.saledate) for each product, using the same query that shows the 3 bestsellers.

You could add max(s.saledate) to your query. The subquery is not needed. The syntax t1 join t2 on <predicate> is considered much more readable than from t1, t2 where <predicate> .

select  top 3 sum(s.individual_sale) as totalsales
,       p.productID as ID,
,       p.productName as Name
,       max(s.saledate) as MaxSaleDate
from    sales s
join    products p
on      p.productID = s.productID
group by
        p.productID
,       p.productName
order by
        sum(s.individual_sale) desc
SELECT TOP(3) *
FROM
(
   SELECT
   SUM(s.individual_sale) AS totalsales,
   p.productID AS ID,
   p.productName AS Name, 
   MAX(s.saledate) as MaxSaleDate

   FROM
   sales s,
   products p

   WHERE
   1=1
   AND p.productID = s.productID

   GROUP BY
   p.productID,
   p.productName
   ) AS top_sellers

ORDER BY
top_sellers.totalsales DESC

Add MAX(saledate) to your exisitng query.

SELECT TOP(3) *
FROM
(
   SELECT
   SUM(s.individual_sale) AS totalsales,
   p.productID AS ID,
   p.productName AS Name,
   MAX(saleDate)

   FROM
   sales s,
   products p

   WHERE
   1=1
   AND p.productID = s.productID

   GROUP BY
   p.productID,
   p.productName
) AS top_sellers

ORDER BY
top_sellers.totalsales DESC

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