从CAse-When-Then获取Group By的多个列

时间:2012-03-28 21:54:19

标签: sql-server tsql

我收到错误在这个查询的','附近的语法不正确 “当3然后kle.Desc,kle.Num”。什么是正确的格式..?

select (case @Type
       when 2 then kle.JNum 
       when 3 then kle.Desc + kle.JNum  
       else kle.LNum end) AS VARCHAR) + @Q + CAST(count(sk.Id) AS VARCHAR) + @Q 
FROM    dbo.SK sk 
INNER JOIN K k  ON K.KITID = SK.KITID
INNER JOIN dbo.MLegend mtl ON k.Type = mtl.MType
INNER JOIN dbo.KLegend kkl ON mtl.KitType = kkl.KitType
INNER JOIN dbo.KExpiry kle on k.ExpiryId= kle.ExpiryId
WHERE SK.SId=Id 
GROUP BY case @Type 
    when 2 then kle.JNum 
    when 3 then kle.Desc, kle.JNum 
    else kle.LNum end, mtl.ktype
ORDER BY mtl.KType

提前致谢。

1 个答案:

答案 0 :(得分:1)

重复案例部分是逗号。

select (case @Type
       when 2 then kle.JNum 
       when 3 then kle.Desc + kle.JNum  
       else kle.LNum end) AS VARCHAR) + @Q + CAST(count(sk.Id) AS VARCHAR) + @Q 
FROM    dbo.SK sk 
INNER JOIN K k  ON K.KITID = SK.KITID
INNER JOIN dbo.MLegend mtl ON k.Type = mtl.MType
INNER JOIN dbo.KLegend kkl ON mtl.KitType = kkl.KitType
INNER JOIN dbo.KExpiry kle on k.ExpiryId= kle.ExpiryId
WHERE SK.SId=Id 
GROUP BY case @Type 
    when 2 then kle.JNum 
    when 3 then kle.Desc + kle.JNum 
    else kle.LNum end, mtl.ktype
ORDER BY mtl.KType