SQL CASE混淆了我的分组

时间:2017-08-31 08:48:33

标签: sql-server tsql case

问题出现在SELECT语句的第4行:CASE WHEN ct.TransactionReason=622 THEN ABS(ct.netquantity) ELSE c.RealNetWeight END AS NetWeight

当我将此行添加到语句中时,我的分组将会更改。它现在不再返回一行,而是返回不同c.realnetweight的行数。 问题是我只想返回一行。有点类似于合并,当有ct.transactionreason = 622时,它应该给我ABS(ct.netquantity),否则为c.realnetweight。代码可以在下面找到,建议会非常有帮助。感谢。

   SELECT   CASE WHEN P.Wrapped = 1 THEN T.[Level]+1 ELSE T.[Level] END AS [Level]
        , @CoilId AS CoilId
        , c.SupplierCoilID
        , CASE WHEN ct.TransactionReason=622 THEN ABS(ct.netquantity) ELSE c.RealNetWeight END AS NetWeight
        , C.RealGrossWeight
        , p1.Description
        , p1.product
        , s.StackID
        , s.ProductID
        , s.Weight
        , P.Product
        , P.Description AS 'ProductDescription'
        , COUNT(t.BlankId) AS 'NumberOfBlanks'
        , c1.Description as 'Status'
        , pv.ProductionWeight
        , pv.BlankWeight
        , t.BlankStatus

FROM @Trace T
    INNER JOIN SKUTraceability SKUT ON SKUT.SKUID = T.SKUID 
    INNER JOIN Stack s ON SKUT.StackID = s.StackID
    INNER JOIN Product p ON s.ProductID = p.ProductID
    INNER JOIN Coil c ON c.CoilID=@CoilId
    INNER JOIN CoilTransaction ct on ct.CoilID=@CoilId
    INNER JOIN Product p1 ON c.ProductID=p1.ProductID
    INNER JOIN Code c1 ON t.BlankStatus=c1.codenumber AND c1.codetypeid=17 
    INNER JOIN @ProductVersion pv ON pv.ProductID=p.ProductId AND s.ProductVersion = pv.ProductVersion

WHERE t.BlankId IS NOT NULL

GROUP BY  T.[Level]
        , c.SupplierCoilID
        , CASE WHEN ct.TransactionReason=622 THEN ABS(ct.netquantity) ELSE c.RealNetWeight END
        , c.RealGrossWeight
        , p1.Description
        , p1.product
        , s.StackID
        , s.ProductID
        , s.Weight
        , p.Product
        , p.Description
        , c1.Description
        , pv.ProductionWeight
        , pv.BlankWeight 
        , p.Wrapped
        , t.BlankStatus

2 个答案:

答案 0 :(得分:0)

如果不理解您的表结构,很难回答,CoilTransaction似乎是某种交易表,即单个产品可能有很多交易。

SELECT查询中,导致您发出问题的行是唯一引用您的CoilTransaction表的行,因此我相信,您返回多行的原因是因为您&#39 ;重新分组不唯一的值。此外,交易是单个项目,因为您似乎在表格上有数量列。

简而言之,您无法通过在交易表中包含这些列来获得所需的分组。您需要详细说明您为实现更合适的解决方案而尝试完成的任务。那条线是什么意思?

答案 1 :(得分:0)

对于表格CoilID中的至少一个Coil,表格netquantity中的字段CoilTransaction中将包含多个值。当您在CASE语句中包含此字段时,这会导致返回的记录数量增加。

我建议您在CTE中从netquantity中找到所需的CoilTransaction值,然后将其添加到CASE语句中。例如:

;WITH transaction_summary AS (
 SELECT
  ct.CoilID,
  ct.TransactionReason,
  MAX(ct.netquantity) -- choose your aggregate function here
 FROM
  CoilTransaction ct
 GROUP BY
  ct.CoilID,
  ct.TransactionReason
)
...