Search code examples
sql-server-2008group-byin-subquery

How to do a Query on SQL Server 2008 R2 using a subquery / function on GROUP BY


When I execute this query, it works fine:

SELECT     
pr.pr_nombre , cl.cl_nomcorto, 
mc_cant * dbo.tipo_cambio(cr.mo_id,3,mc_fecha)/0.951 as Interes,
mc_cant * dbo.tipo_cambio(cr.mo_id,3,mc_fecha)/0.951*.049 as WH,
(select pr_id from dbo.nonplusultra(cr.pr_id) where pr_renew_ref is null) as Agrupador
FROM   movcuentas mc
inner join corridas cr on mc.cr_id =  cr.cr_id
inner join clientes cl on cr.cl_id = cl.cl_id
inner join prestamos pr on cr.pr_id = pr.pr_id
WHERE     (mc_concepto = 'Amort Int') AND (tm_id = 3) AND MONTH(mc_fecha) = 2 AND YEAR(mc_fecha) = 2017 
ORDER BY pr.pr_nombre

I get this:

Query results

Now I need to show it adding columns "Interes" and "WH" on records with same "Agrupador", something like this:

SELECT     
pr.pr_nombre , cl.cl_nomcorto, 
sum(mc_cant * dbo.tipo_cambio(cr.mo_id,3,mc_fecha)/0.951) as Interes,
sum(mc_cant * dbo.tipo_cambio(cr.mo_id,3,mc_fecha)/0.951*.049) as WH,
(select pr_id from dbo.nonplusultra(cr.pr_id) where pr_renew_ref is null) as Agrupador
FROM   movcuentas mc
inner join corridas cr on mc.cr_id =  cr.cr_id
inner join clientes cl on cr.cl_id = cl.cl_id
inner join prestamos pr on cr.pr_id = pr.pr_id
WHERE     (mc_concepto = 'Amort Int') AND (tm_id = 3) AND MONTH(mc_fecha) = 2 AND YEAR(mc_fecha) = 2017 
GROUP BY pr.pr_nombre , cl.cl_nomcorto, (select pr_id from dbo.nonplusultra(cr.pr_id) where pr_renew_ref is null)
ORDER BY pr.pr_nombre

And I get this error message:

Msg 144, Level 15, State 1, Line 12 Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.

Any help will be welcome.


Solution

  • Can you make use of CTE here?

    ;WITH CTE as 
    (
    SELECT     
    pr.pr_nombre , cl.cl_nomcorto, 
    mc_cant * dbo.tipo_cambio(cr.mo_id,3,mc_fecha)/0.951 as Interes,
    mc_cant * dbo.tipo_cambio(cr.mo_id,3,mc_fecha)/0.951*.049 as WH,
    (select pr_id from dbo.nonplusultra(cr.pr_id) where pr_renew_ref is null) as Agrupador
    FROM   movcuentas mc
    inner join corridas cr on mc.cr_id =  cr.cr_id
    inner join clientes cl on cr.cl_id = cl.cl_id
    inner join prestamos pr on cr.pr_id = pr.pr_id
    WHERE     (mc_concepto = 'Amort Int') AND (tm_id = 3) AND MONTH(mc_fecha) = 2 AND YEAR(mc_fecha) = 2017 
    ORDER BY pr.pr_nombre
    )
    select pr_nombre,cl_nomcorto,sum(Interes),sum(WH),Agrupador
    from CTE
    group by pr_nombre,cl_nomcorto,Agrupador
    order by pr_nombre