如何总结具有相同值的数据?

时间:2015-03-30 01:33:42

标签: php mysql sql database

我想总结一下我的数据库中的状态总数。如果我有status = 0,我想要计算所有状态= 0的实例。我已经尝试过这段代码,但总和并不匹配我的数据库。

SELECT t.date as Date, COUNT(DISTINCT t.id) as Transaction, SUM(t.status=0) as Success, COUNT(DISTINCT r.id) as Request, SUM(r.status=0) as RequestSuccess 
FROM transfer_tx_201503 AS t,request_tx_201503 AS r 
WHERE t.time >='00:00:00' AND t.time <= '$searchterm' AND t.date=r.date 
GROUP BY `date` 

1 个答案:

答案 0 :(得分:0)

您正确编写的查询是:

SELECT t.date as Date, COUNT(DISTINCT t.id) as Transaction, SUM(t.status=0) as Success, COUNT(DISTINCT r.id) as Request, SUM(r.status=0) as RequestSuccess 
FROM transfer_tx_201503 t JOIN
     request_tx_201503 r 
     ON t.date = r.date 
WHERE t.time >='00:00:00' AND t.time <= '$searchterm' 
GROUP BY `date` 

(注意ON子句和显式JOIN ...这是将两个表连接在一起的正确方法。)

您的问题是您获得了给定date的笛卡尔积,因为每个表中的多行与日期匹配。最好的解决方案是预先汇总结果:

SELECT t.date as Date, t.Transaction, t.Success, r.Request, r.RequestSuccess 
FROM (select date, count(*) as transaction, sum(t.status = 0) as success
      from transfer_tx_201503 t
      group by date
     ) t JOIN
     (select date, count(*) as Requestion, SUM(r.status = 0) as RequestSuccess
      from request_tx_201503 r 
      group by date
     ) r
     ON t.date = r.date 
WHERE t.time >='00:00:00' AND t.time <= '$searchterm' ;

请注意,您不再需要外部group by。您还可以在每个子查询中包含where子句。如果这是一个问题,这可能会提高性能。