0

假设我想选择超市中的 3 个畅销书。为此,我必须将每笔销售相加,以获得每种产品的总数:

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

然后它返回给我这样的东西:

ID..|.姓名。|.totalsales

55.|.牛奶....|.1000

24.|.糖果。|.800

67.|.果汁...|.500

现在我想从这些项目中检索包含最后一次销售的第 4 列,例如查询每个项目的“MAX saledate”。我该如何做到这一点?

编辑:添加 MAX(s.saledate) 没有帮助。它会在所有行中检索像 2012 年 1 月 1 日这样的日期,但是如果我为上表的每个条目单独查询 MAX(s.saledate),它会返回正确的日期...我的问题是,如何添加 MAX 列(s.saledate),使用显示 3 个畅销书的相同查询。

4

3 回答 3

2

您可以添加max(s.saledate)到您的查询。不需要子查询。该语法t1 join t2 on <predicate>被认为比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
于 2013-03-13T17:05:00.710 回答
0
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
于 2013-03-13T17:07:01.003 回答
0

添加MAX(saledate)到您现有的查询。

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
于 2013-03-13T17:07:41.667 回答