SQL最高价值与组

时间:2014-10-17 10:35:34

标签: sql sql-server

我需要做的是获取最高StockOnSiteProductID(计算StockDifference)记录并将StockOnSite连接到StockOffsite以创建一个列AllStock

我完全失去了?因为我没有分组,因为我们有StockOnSite和StockOffsite

这是SQLFiddle

Fiddle

这不是重复的帖子,因为外部选择会使分组变得复杂。

由于

3 个答案:

答案 0 :(得分:1)

我相信这是您一直在寻找的查询。

它会根据您的建议评估StockDiffStockOnSite - StockOffSite,然后为每个SiteID

取最高值
SELECT
  SiteID, Description, StockOnSite, StockOffsite, AllStock, LastStockUpdateDateTime, StockDiff
FROM (
  SELECT 
    *,
    rank() OVER (PARTITION BY SiteID ORDER BY StockDiff DESC) AS rank
  FROM (
      SELECT
        s.SiteID,
        s.Description, 
        p.StockOnSite, 
        p.StockOffsite, 
        CAST(p.StockOnSite AS varchar(10)) + '/' + CAST(p.StockOffSite AS varchar(10)) AS AllStock,
        p.LastStockUpdateDateTime,
        p.StockOnSite - p.StockOffSite AS StockDiff
      FROM 
        Sites s 
        JOIN Products p ON s.SiteID = p.OnSiteID
      ) foo
    ) goo
WHERE rank = 1
ORDER BY 1

我用Window function来完成它。

修改

如果您需要最高StockOnSite,则可以使用StockDiff

替换ORDER BY StockDiff DESC中的StockOnSite,轻松修改窗口函数

答案 1 :(得分:0)

您想通过ProductID获得最高的StockOnSite,但样本集都具有唯一的productID。此查询将获得您要求的内容,但我认为您的问题可能不清楚您的结果集应该是什么样的。

select  pr.ProductID
, s.SiteID
 ,s.Description
 ,StockOnSite
 ,StockOffsite
 ,AllStock = cast(coalesce(pr.StockOnSite,'') as varchar(10)) + '-' + cast(coalesce(pr.StockOffsite,'') as varchar(10)) 
 ,LastStockUpdateDateTime = pr.LastStockUpdateDateTime
 ,Stockdiff = StockOnSite - StockOffsite
from Products pr
inner join (
  select    pr.ProductID
  , MAX(StockOnSite) MaxStockOnSite
  from dbo.Products pr
  group by [ProductID]
) x
ON x.ProductID = pr.ProductID
and x.MaxStockOnSite = pr.StockOnSite
inner join dbo.Sites s
ON pr.OnSiteId = s.SiteId

答案 2 :(得分:0)

此查询可能对您有所帮助:

select * from Products p1
join
(
  select onsiteid,max(stockonsite-stockoffsite) as stockdiff
  from products
  group by onsiteid
) p2
on p1.onsiteid = p2.onsiteid and (p1.stockonsite - p1.stockoffsite) = p2.stockdiff

您可以根据需要修改选择。