Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to union two queries in stored procedure to get result in one row

Tags:

sql-server

I have a stored procedure in which I joined two queries. my queries are

alter PROCEDURE test

@SDate datetime,
@EDate datetime

As

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
(Select count(quoteid) as TotalQuote, sum(totalamount) as QuoteAmount from dbo.QuoteBase
where CreatedOn BETWEEN @SDate AND @EDate) 
union All

(select  count(salesorderid)as TotalOrders, sum(totalamount) as OrderAmount from dbo.SalesOrderBase Where
CreatedOn BETWEEN @SDate AND @EDate)

and I got result in to column

Total Quote    Quote Amount
17                   700
118                 5000

but I want result like

Total Quote    Quote Amount    Total Orders   Order Amount
  17               700              118           5000

If anyone have idea please share with me

like image 377
riaz.usmani Avatar asked Jun 03 '13 10:06

riaz.usmani


People also ask

Can we combine the rows from two tables by using UNION clause?

The Union operator combines the results of two or more queries into a distinct single result set that includes all the rows that belong to all queries in the Union. In this operation, it combines two more queries and removes the duplicates.

Does UNION help in row wise addition of data?

Unions combine data into new rows. If two tables are “unioned” together, then the data from the first table is in one set of rows, and the data from the second table in another set. The rows are in the same result.


1 Answers

Try this one -

ALTER PROCEDURE dbo.usp_test

      @SDate DATETIME 
    , @EDate DATETIME

AS BEGIN

    SET NOCOUNT ON;

    SELECT 
          t.TotalQuote
        , t.QuoteAmount
        , t2.TotalOrders
        , t2.OrderAmount
    FROM (SELECT a = 1) a
    CROSS JOIN (
        SELECT 
              TotalQuote = COUNT(quoteid)
            , QuoteAmount = SUM(totalamount)
        FROM dbo.QuoteBase
        WHERE CreatedOn BETWEEN @SDate AND @EDate
    ) t
    CROSS JOIN (
        SELECT 
              TotalOrders = COUNT(salesorderid)
            , OrderAmount = SUM(totalamount) 
        FROM dbo.SalesOrderBase
        WHERE CreatedOn BETWEEN @SDate AND @EDate
    ) t2

END

Update:

SELECT 
      t.TotalQuote
    , t.QuoteAmount
    , t2.TotalOrders
    , t2.OrderAmount
FROM (
    SELECT 
          TotalQuote = COUNT(quoteid)
        , QuoteAmount = SUM(totalamount)
    FROM dbo.QuoteBase
    WHERE CreatedOn BETWEEN @SDate AND @EDate
) t
FULL OUTER JOIN
(
    SELECT 
          TotalOrders = COUNT(salesorderid)
        , OrderAmount = SUM(totalamount) 
    FROM dbo.SalesOrderBase
    WHERE CreatedOn BETWEEN @SDate AND @EDate
) t2 ON 1 = 1
like image 137
Devart Avatar answered Sep 29 '22 10:09

Devart