如何从子查询中选择每行的最大日期

时间:2013-03-13 17:02:53

标签: sql tsql

假设我想在超市中选择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 .. |请将.Name |。.totalsales

55. | .milk .... | 0.1000

24. | .candy |。0.800

67. | .juice ... | 0.500

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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