使用Case和Subquery进行分组

时间:2014-06-27 10:23:06

标签: sql sql-server

使用以下SQL执行分组时遇到问题:

SELECT 
    CASE 
         WHEN  t = '11' then 'V' 
         WHEN (t = '20' OR t = '25') THEN 'S' 
    END as [ty],

    CONVERT(CHAR(3), DateEx, 101) + CONVERT(CHAR(4), DateEx, 120) as [Fecha], COUNT(*) as [Total],  
    SUM (case when  CodLastEstado in (3,4,5,6,7,10,11,12,13) then 1 else 0 end ) as [C1],
    SUM (case when  CodLastEstado in (4,5,6) then 1 else 0 end ) as [C2],
    (
    select COUNT(*)
    from (SELECT t.Line, t.VTO, t.SubTypo
          FROM (SELECT c.Line, CONVERT(CHAR(3), c.DateEx, 101) + CONVERT(CHAR(4), c.DateEx, 120) as [VTO],
                       ROW_NUMBER() OVER (PARTITION BY a.numid ORDER BY a.FechaAccion desc) as Fila, SubTypo
                FROM Acciones a, contratos c
                WHERE A.numid = c.numid
                      AND (c.CodLastEstado in (10,11) and a.IDCodTipoEstado in (4,5,6)) 
                      and c.Brand = 'mouse'             
               ) t
          where t.Fila = 1
         )as q   
    where q.VTO = CONVERT(CHAR(3), contratos.DateEx, 101) + CONVERT(CHAR(4), contratos.DateEx, 120)
    and q.SubTypo = contratos.SubTypo
    ) as [CHco],    
    SUM (case when  CodLastSubEstado in (56,46,36,3,13,24) then 1 else 0 end ) as [N],
 FROM contratos
WHERE Brand = 'MINI' AND DateEx between '01/11/2014' and '30/11/2014'
GROUP BY SubTypo,
CONVERT(CHAR(3), contratos.DateEx, 101) + CONVERT(CHAR(4), contratos.DateEx, 120)

语法正确,显示如下:

ty||Total||C1||C2||CHco||N

S || 120 ||5 ||50||  3 ||0
S ||   1 ||0 ||0 ||  1 ||0
V ||   3 ||0 ||0 ||  0 ||0

我尝试过很多东西要显示如下,但我没有,有什么想法?

ty||Total||C1||C2||CHco||N

S || 121 ||5 ||50||  4 ||0
V ||   3 ||0 ||0 ||  0 ||0

2 个答案:

答案 0 :(得分:1)

...或者您可以使用公用表表达式:

WITH UngroupedData AS (
--Your query
)
SELECT
    [ty],
    SUM([Total]) AS [Total],
    SUM([C1]) AS [C1],
    SUM([C2]) AS [C2],
    SUM([CHco]) AS [CHco],
    SUM([N]) AS [N]
FROM
    UngroupedData
GROUP BY
    [ty];

答案 1 :(得分:0)

可能不是最快的解决方案,但只要你有一个想要重新聚合的结果,就可以用子选择它。

SELECT ty, 
  SUM(C1) as [C1], 
  SUM(C2) as [C2], 
  SUM(CHco) as [CHCo], 
  SUM(N) as [N]
FROM (
  // your original query
) as subselect
GROUP BY ty