MySQL根据另一个不同的列数对一列进行求和

时间:2016-03-20 10:36:23

标签: mysql

我需要根据不同的 ... more code here ... ieApp.Navigate "http://www.website.com/blabla" Do While ieApp.Busy: Sleep 500: DoEvents: Loop Do Until ieApp.readyState = READYSTATE_COMPLETE: DoEvents: Loop Set rcl = ieApp.Document.getElementsbyClassName("col-md-3") For Each ahref In rcl(0).getElementsByTagName("a") ieApp.Navigate ahref.href Do While ieApp.Busy: Sleep 500: DoEvents: Loop Do Until ieApp.readyState = READYSTATE_COMPLETE: DoEvents: Loop ' Now get the data Call subSaveRecords Next ... continue more ...

获得hits的总和

到目前为止,这是我提出的:

ip

示例数据:

SELECT 
COUNT(DISTINCT `ip`) AS `total`, 
SUM(`hits`) AS `sum` 
FROM `stats`.`stats` 
WHERE `category`=? 
GROUP BY `date`

预期结果:

|  category |  ip   |  hits  |  date   |
|  11       |  ip1  |  1000  |  date1  |
|  11       |  ip2  |  1000  |  date1  |
|  11       |  ip3  |  1000  |  date1  |
|  11       |  ip4  |  1000  |  date1  |
|  11       |  ip1  |  1000  |  date1  |

我正在

ip=4
sum=4000

但是,如果仅对不同的ip命中进行求和,则会给出总ip命中率。

请建议一种方法来做到这一点。我更喜欢做像

这样的事情
ip=4
sum=5000

而不是子查询,因为我需要快速查询。 使用SUM(CASE WHEN `ip` THAN `hits`) //or SUM(CASE WHEN IN(`ip`) THAN `hits`) //or SUM(CASE WHEN IF(`ip`) THAN `hits`) PHP方面对我也有好处。

3 个答案:

答案 0 :(得分:3)

你可以这样做:

SELECT count(s.ip) as cntIp,sum(s.hits) as sumHits 
FROM(
    SELECT DISTINCT t.ip,t.hits
    FROM YourTable t) s

但看起来你提供的数据不准确,我看到你按日期分组,这意味着日期等于而不是像你的例子中的date1,date2,date3 ......

所以:

SELECT s.date,count(s.ip) as cntIp,sum(s.hits) as sumHits 
FROM(
    SELECT DISTINCT t.ip,t.hits,t.date
    FROM YourTable t) s
GROUP BY s.date

修改

SELECT s.date,count(s.ip) as cntIp,sum(s.hits) as sumHits 
FROM(
    SELECT t.ip,t.hits,t.date
    FROM YourTable t
    GROUP BY t.ip,t.hits,t.date) s
GROUP BY s.date

答案 1 :(得分:1)

您需要编写一个子查询,返回每个ip / date的最小命中值。然后你可以总结这些。

SELECT date, count(*) as sum, sum(minhits) as hits 
FROM(
    SELECT ip, date, MIN(hits) AS minhits
    FROM stats
    WHERE category = ?
    GROUP BY ip, date) AS subquery
GROUP BY date

答案 2 :(得分:0)

你可以试试这个

SELECT 
    `ip`
    COUNT(`ip`) AS `total`, 
    SUM(`hits`) AS `sum` 
FROM 
    `stats`.`stats` 
WHERE 
    `category`=? 
GROUP BY        
    `date`,
     `ip`