How to combine the results of two queries?

大憨熊 提交于 2021-01-29 08:33:37

问题


I created a procedure that has two selects, I want to join the result of these two selects in one.

This is my procedure

CREATE PROCEDURE spConsultarVendas
    @nomeUsuario nvarchar(60), 
    @dataEmissao datetime, 
    @dataSaida datetime 
AS
BEGIN
    SELECT
        NF.ID, NF.NaturezaOperacao, NF.DataEmissao, NF.ValorTotal
    FROM   
        NotaFiscal AS NF
    INNER JOIN
        Venda AS V ON NF.ID_Venda = V.ID
    INNER JOIN
        Usuario AS U ON V.ID_UsuarioComissao1 = U.ID
    WHERE
        U.Descricao = @nomeUsuario 
        AND (NF.DataEmissao >= @dataEmissao AND NF.DataSaida <= @dataSaida)

    SELECT
        SUM(NF.ValorTotal) AS FinalValue
    FROM
        NotaFiscal AS NF
    INNER JOIN
        Venda AS V ON Nf.ID_Venda = V.ID
    INNER JOIN
        Usuario AS U ON V.ID_UsuarioComissao1 = U.ID
    WHERE
        U.Descricao = @nomeUsuario 
        AND (NF.DataEmissao >= @dataEmissao AND NF.DataSaida <= @dataSaida)
END

These are the results:

I want to combine these results into one.


回答1:


You can add the final result easily to each row of the first query:

SELECT NF.ID, NF.NaturezaOperacao, NF.DataEmissao, NF.ValorTotal,
       SUM(NF.ValorTotal) OVER () AS ValorFinal
FROM NotaFiscal NF INNER JOIN
     Venda V
     ON NF.ID_Venda = V.ID INNER JOIN
     Usuario U
     ON V.ID_UsuarioComissao1 = U.ID
WHERE U.Descricao = @nomeUsuario AND
      (NF.DataEmissao >= @dataEmissao AND NF.DataSaida <= @dataSaida)


来源:https://stackoverflow.com/questions/61019965/how-to-combine-the-results-of-two-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!