Put two results together in the same table

0

I'm trying to get two different queries together in the same table:

    declare @semana nvarchar(10)
    set @semana=(select datepart(week,getdate()))

    select SUM(CANTIDAD) AS Qty1 from tbl_Entrada where dia=('Monday')  and semana=@semana --Primer resultado

    select  sum(cantidad) as Qty2 from tbl_Entrada where dia=('Tuesday')  and semana=@semana --Segundo resultado

In this way two results are thrown separately, however I want these results (Qty1, Qty2) appear in one as if it were the same sentence.

    
asked by CarlosR93 03.07.2017 в 22:51
source

2 answers

2

This is not necessary to calculate it in 2 different queries, but it is more efficient in a single query:

DECLARE @semana int; --el resultado es un int, no nvarchar
SELECT @semana = DATEPART(WEEK,GETDATE()); -- esta es la sintaxis correcta

SELECT SUM(CASE WHEN dia = 'Monday' THEN Cantidad END) Qty1,
       SUM(CASE WHEN dia = 'Tuesday' THEN Cantidad END) Qty2
FROM tbl_Entrada 
WHERE dia IN ('Monday','Tuesday')
AND semana = @semana;
    
answered by 03.07.2017 / 22:55
source
1

You can use the UNION operator

select SUM(CANTIDAD) AS Qty from tbl_Entrada where dia=('Monday')  and semana=@semana --Primer resultado
UNION
select  sum(cantidad) as Qty from tbl_Entrada where dia=('Tuesday')  and semana=@semana --Segundo resultado

Note that you must call the same columns in both queries. UNION by default takes only different values, use UNION ALL to get all. However, the specific scenario illustrated can be performed in a query as indicated by Lamak . UNION would be more applicable in cases of having results of two tables or independent queries in general.

    
answered by 03.07.2017 в 23:02