如何从具有不同WHERE条件的同一张表的2个不同列中减去2个值?

时间:2019-05-07 14:43:54

标签: sql sql-server ssms

我试图从同一张表的2个不同列中减去2个求和值,然后将单个值插入到另一个表中,但求和值的取值条件不同,我似乎找不到解决方法! / p>

第一个qry:

SELECT SUM(ticketTotalAmount)
 FROM tickets
WHERE ticketDate > dateadd(hh,-1,getdate()) 
    AND ticketDate < GETDATE() AND ticketState IN ('STAND BY' , 'WIN' , 'LOSE')

第二遍:

select SUM(ticketTotalWin) 
FROM tickets 
WHERE ticketDate > dateadd(hh,-1,getdate()) AND ticketDate < GETDATE()
     AND ticketState = 'WIN'

我必须从查询结果中减去这些值: 首先-第二,然后将其插入到另一个表的单列中,我将值插入另一个表的方式如下:

insert into ticketsAmounts (totalAmountPlay, totalAmountStandBy, totalAmountLose, totalAmountRefused, totalAmountWin, totalAmountClosed, totalAmountPayout, totalAmountRating, totalTickets)
SELECT
    (select SUM(ticketTotalAmount) 
     from tickets
    where ticketDate > dateadd(hh,-1,getdate()) 
         AND ticketDate < GETDATE()
         AND ticketState IN ('STAND BY' , 'WIN' , 'LOSE')),
    (select SUM(ticketTotalAmount) 
       from tickets 
       where ticketDate > dateadd(hh,-1,getdate()) 
       AND ticketDate < GETDATE() AND ticketState = 'STAND BY'),
    (select SUM(ticketTotalAmount) 
      from tickets
      where ticketDate > dateadd(hh,-1,getdate()) 
      AND ticketDate < GETDATE() AND ticketState = 'LOSE'),

这只是一部分,但您明白了,这两个求和值也都插入到table2的列中,我尝试将selects放入select中,但它不起作用,而且看起来很可怕!

2 个答案:

答案 0 :(得分:2)

您希望有条件地汇总差异:

SELECT (SUM(ticketTotalAmount) -
        SUM(CASE WHEN ticketState = 'WIN' THEN ticketTotalWin ELSE 0 END)
       ) as diff
FROM tickets
WHERE ticketDate > dateadd(hour, 1, getdate()) AND
      ticketDate < GETDATE() AND
      ticketState IN ('STAND BY', 'WIN' , 'LOSE');

我看不到insert的其他列如何计算,但是我怀疑可以使用相同的方法。

答案 1 :(得分:1)

尝试一下。现在,您可以轻松计算两个SUM结果之间的差异。

SELECT 
SUM(
        CASE 
            WHEN ticketState IN ('STAND BY' , 'WIN' , 'LOSE') THEN ticketTotalAmount 
            ELSE 0 
        END
) AS TotalAmount,
SUM(
        CASE 
            WHEN ticketState = 'WIN' THEN ticketTotalWin 
            ELSE 0 
        END
) AS TotalWin
FROM tickets
WHERE ticketDate > DATEADD(hh,-1,GETDATE()) AND ticketDate < GETDATE()

要获得两个和之间的差,只需使用以下查询即可返回单个值。您也可以将其用于插入目的。

SELECT 
SUM(
        CASE 
            WHEN ticketState IN ('STAND BY' , 'WIN' , 'LOSE') THEN ticketTotalAmount 
            ELSE 0 
        END
) -
SUM(
        CASE 
            WHEN ticketState = 'WIN' THEN ticketTotalWin 
            ELSE 0 
        END
) AS TotalDifference
FROM tickets
WHERE ticketDate > DATEADD(hh,-1,GETDATE()) AND ticketDate < GETDATE()