GROUP BY WITH HAVING(DISTINCT):PHP,MYSQL

时间:2015-08-18 07:24:19

标签: mysql count group-by sum having

id | mid | pid | owgh | nwgh |
1    3      12    1.5    0.6
2    3      12    1.5    0.3
3    3      14    0.6    0.4
4    3      15    1.2    1.1
5    4      16    1.5    1.0
6    4      17    2.4    1.2 
7    3      19    3.0    1.4

从上面我想要nwgh的中间和总和的总数。 id ex:mid = 3或mid = 4 但是使用DISTINCT pid但请注意nwgh的总和不应该是DISTINCT

因此我的结果如下:

mid  | countmid            |   totalnwgh
3      4 (DISTINCT value)      3.8 (no DISTINCT it take both value of pid =12)
4      2                       2.2

在上面的结果中= 3有计数4因为pid = 12重复因此它的DISTINCT 但是nwgh不应该是DISTINCT,它的总计数

我尝试了什么

Select mid , COUNT(mid) as countmid  , SUM(nwgh) as totalnwgh from test where mid = 3
GROUP BY mid HAVING count(DISTINCT pid)

2 个答案:

答案 0 :(得分:4)

如果我了解您的需求,您只需在 COUNT 中执行不同

你可以试试这个:

SELECT mid , 
    COUNT(distinct pid) as countmid  , 
    SUM(nwgh) as totalnwgh 
FROM test 
GROUP BY mid 

如果需要,请尝试此sqlfiddle:official doc

答案 1 :(得分:0)

使用此

ThreadStart job = new ThreadStart(() =>
{
    foreach (var ticker in tickers)
    {
       var url = string.Format(urlPrototype, ticker, startMonth, startDay, startYear, finishMonth, finishDay, finishYear, "d");
       var csvfile = directory + "\\" + ticker.ToUpper() + ".csv";
       webClient.DownloadFile(url, csvfile);    
       numStocks++;
    }
    Dispatcher.BeginInvoke((Action)(()=> tbOutput.Text += "End Download of : " + ticker + "\n";}));

});

Thread thread = new Thread(job);
thread.Start();