在一行中将SUM与UNION ALL一起使用

时间:2019-02-23 05:27:24

标签: sql sql-server

我有以下query

    SELECT SUM(totalCantidad) AS totalCantidad,
           SUM(totalPrecio) AS totalPrecio
    FROM(
           SELECT  SUM(dt1.cantidad) AS totalCantidad,
                   SUM(dt1.cantidad*dt1.precio) AS totalPrecio
           FROM Det_materiales dt1
           INNER JOIN Materiales ma ON ma.factura=dt1.factura
           WHERE ma.factura='1848'
         UNION ALL
           SELECT SUM(dt2.cantidad) AS totalCantidad,
                  SUM(dt2.cantidad*p.precio) AS totalPrecio
           FROM Det_mate2 dt2
           INNER JOIN Materiales ma ON ma.factura=dt2.factura
           INNER JOIN Partes p ON p.cod_parte=dt2.cod_parte
           WHERE ma.factura='1848'
       )x GROUP BY totalCantidad

它向我返回:

enter image description here

是否可以在一行中生成两个SUM(),如下所示:

totalCantidad-----totalPrecio
16909             63550,169

我还需要从FROM打印数据,但是我不知道如何显示它,换句话说,我需要这样:

factura-----other data-----totalCantidad-----totalPrecio
1848         xxxxxx          16909             63550,169

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作-删除GROUP BY totalCantidad

 SELECT factura,SUM(totalCantidad) AS totalCantidad,
           SUM(totalPrecio) AS totalPrecio
    FROM(
           SELECT  ma.factura,SUM(dt1.cantidad) AS totalCantidad,
                   SUM(dt1.cantidad*dt1.precio) AS totalPrecio
           FROM Det_materiales dt1
           INNER JOIN Materiales ma ON ma.factura=dt1.factura
           WHERE ma.factura='1848' group by ma.factura
         UNION ALL
           SELECT ma.factura, SUM(dt2.cantidad) AS totalCantidad,
                  SUM(dt2.cantidad*p.precio) AS totalPrecio
           FROM Det_mate2 dt2
           INNER JOIN Materiales ma ON ma.factura=dt2.factura
           INNER JOIN Partes p ON p.cod_parte=dt2.cod_parte
           WHERE ma.factura='1848' group by ma.factura
       )x group by factura