SQL GROUP BY不能为两个表的组合返回正确的结果

时间:2018-10-10 06:52:41

标签: sql sql-server group-by

我是SQL新手,遇到麻烦了。我有两个桌子:
1. TopStock : Id |RuyeId| Code |ModelId|Quantity|ColorId
.............: 1 | 1019 |290105| 44 | 100 | 23
.............: 2 | 1019 |290105| 44 | 150 | 23
.............: 3 | 1019 |290105| 44 | 400 | 19
.............: 4 | 1019 |290105| 44 | 50 | 23
.............: 4 | 1018 |280102| 21 | 800 | 14

2. DownStock : Id|KafiId| Code |Quantity|ColorId
.............: 1 | 1005 | 2901 | 200 | 21


这是我的情况:如果TopStock的{​​{1}}等于{{ 1}}的{​​{1}}。 我想要一个查询,该查询显示每个DownStock s DownStock的总数量以及可能与之结合的DownStock的总数量。

这是我的查询

Code

我想要这个结果:
TopStock
Code
TopStock

实际上,GROUP BY: ModelId,ColorId应该是每个SELECT DISTINCT SUM(top.Quantity) as Quantity, MAX(top.Code) as Code MAX(top.ColorId) as ColorId, MAX(top.ModelId) as ModelId, MAX(top.RuyeId) as RuyeId, SUM(down.Quantity) as DownQuantity FROM TopStock as top JOIN DownStock as down ON top.Code like '%'+down.Code+'%' WHERE top.Status = 0 GROUP BY top.ModelId, top.ColorId, top.Code, down.Code ed Quantity| Code |ColorId|ModelId|RuyeId|DownQuantity项目可能的. 300 |290105| 23 | 44 | 1019 | 200数量的总和。但是查询返回以下内容:
. 400 |290105| 19 | 44 | 1019 | 200
DownQuantity
DownStock

问题:GROUP BY是因为我有3个TopStock行,它们分别具有相同的Quantity| Code |ColorId|ModelId|RuyeId|DownQuantity. 300 |290105| 23 | 44 | 1019 | 600 -> (3*200)。我只想要200否600。有人能解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我删除了MAX的所有用法,您将按列分组,没有理由对其进行聚合,因为只有1个值。另外,请勿同时使用distinct和group by。我还加入了汇总表,以避免连接中的重复

SELECT SUM(top.Quantity) as Quantity,top.Code, top.ColorId, top.ModelId,  
       top.RuyeId, max(down.Quantity) as DownQuantity
FROM TopStock top 
JOIN (SELECT down.code, sum(down.quantity) as quantity FROM DownStock down
      GROUP BY down.code) down
 ON top.Code like '%'+down.Code+'%'
WHERE top.Status = 0
GROUP BY top.ModelId, top.ColorId, top.Code, down.Code  

答案 1 :(得分:1)

尝试使用row_number()窗口函数,如下所示

with t1 as
 (
  select *, row_number() over(partition by ModelId,ColorId order by ColorId desc) rn
 from TopStock
 ) ,t2 as
(
 select t1.* from t1 where t1.rn<=2
) 
 select top.Code, top.ColorId, top.ModelId,  
       top.RuyeId, 
      SUM(top.Quantity) as Quantity,
      max(down.Quantity) as DownQuantity,
      from t2 top join DownStock down
      on top.Code like '%'+down.Code+'%'
      group by top.Code, top.ColorId, top.ModelId,  
       top.RuyeId