将两个SQL查询合并为一个查询

时间:2018-05-09 18:39:19

标签: mysql sql database

我有一个结构表

TicketID - ID of the Ticket
CreateTime - Time when the ticket is created
FinishTime - Time when the ticket is finished handled

我的目标是根据小时

找到这些值
Number of Tickets Received per hour
Number of Tickets handled per hour

到目前为止,我已经进行了2次单独查询

Select count(Receipt.ID) as ReceiveCount,
       Receipt.hours as PST,
      (Receipt.hours+12.5) as IST 
from
      (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID,
              from_unixtime(CreateTime/1000 , '%H') as hours 
       from 
              ReceiptScanRequestTable 
       where 
              CreateTime>{hour_filter_value}  
      ) as Receipt 
Group By 
      Receipt.hours

这将返回每小时收到的门票数

Select count(Receipt.ID) as FinishCount,
           Receipt.hours as PST,
          (Receipt.hours+12.5) as IST 
    from
          (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID,
                  from_unixtime(FinisheTime/1000 , '%H') as hours 
           from 
                  ReceiptScanRequestTable 
           where 
                  CreateTime>{hour_filter_value}  
          ) as Receipt 
    Group By 
          Receipt.hours

这将返回每小时完成的门票数

我的目标是将两个查询合并为一个!

2 个答案:

答案 0 :(得分:0)

试试这个:

select receivecount, finishcount from (Select count(Receipt.ID) as ReceiveCount,
       Receipt.hours as PST,
      (Receipt.hours+12.5) as IST 
from
      (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID,
              from_unixtime(CreateTime/1000 , '%H') as hours 
       from 
              ReceiptScanRequestTable 
       where 
              CreateTime>{hour_filter_value}  
      ) as Receipt 
Group By 
      Receipt.hours) a 
cross apply
(Select count(Receipt.ID) as FinishCount,
           Receipt.hours as PST,
          (Receipt.hours+12.5) as IST 
    from
          (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID,
                  from_unixtime(FinisheTime/1000 , '%H') as hours 
           from 
                  ReceiptScanRequestTable 
           where 
                  CreateTime>{hour_filter_value}  
          ) as Receipt 
    Group By 
          Receipt.hours)b

答案 1 :(得分:0)

您可以使用union all然后汇总:

select hours, sum(receive) as numreceived, sum(finish) as numfinished,
       (hours + 12.5) as IST 
from ((Select from_unixtime(CreateTime/1000 , '%H') as hours, 1 as receive, 0 as finish
       from ReceiptScanRequestTable 
       where CreateTime > {hour_filter_value}
      ) union all
      (Select from_unixtime(FinisheTime/1000 , '%H') as hours, 0, 1
       from ReceiptScanRequestTable 
       where CreateTime>{hour_filter_value}  
      )
     ) r
group by hours;