簡體   English   中英

在按功能分組的多列上的sum()

[英]sum() on multiple columns with group by function

我需要從每一列收集計數,並且每一行都有多個結果。 問題在於這些列正在復制第一列的值。

  $sql="SELECT MODEL, 
     sum(CLICK) AS LOCCLICK, sum(VIEW) AS LOCVIEW, sum(EMAIL) AS LOCEMAIL, sum(SHARE) AS LOCSHARE
      FROM     STAT
      WHERE    ID = ".$id."
      GROUP BY MODEL";
       $result = $mysqli->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                $clickcoun = $row['LOCCLICK'];
                $viewcoun = $row['LOCVIEW'];
                $emailcoun = $row['LOCEMAIL'];
                $sharecoun = $row['LOCSHARE'];
                $model = $row['MODEL'];
                echo "\n";
                // Log the stats into the daily updates.
                 $sqlx = 'INSERT INTO DAILY (ID, QDATE, VIEWS, CLICKS, EMAILS, SHARES, MODEL) 
                VALUES ('.$id.', NOW(), '.$viewcoun.', '.$clickcoun.', '.$emailcoun.', '.$sharecoun.', "'.$model.'" )';
                  $mysqli->query($sqlx);
                  } 
                 } else {
                      echo "0 results"; die();
                 }

我正在尋找的結果如下:

福特:瀏覽次數= 302,電子郵件= 21,份額= 10

道奇:觀看次數= 567,電子郵件= 41,份額= 13

雪佛蘭:觀看次數= 324,電子郵件= 23,分享次數= 9

我想將這些數據輸入到每日統計數據細分中,以便查詢它們並將它們放入圖表中並顯示其每日覆蓋率。 在本月底,我計划以相同的方式再次分解這些內容,以進行每月概覽。

您不需要循環即可執行此操作。 只需使用insert . . . select insert . . . select insert . . . select

INSERT INTO DAILY (ID, MODEL, CLICKS, VIEWS, EMAIL, SHARES, QDATE) 
    SELECT $id, MODEL, sum(CLICK) AS LOCCLICK, sum(VIEW) AS LOCVIEW,
           sum(EMAIL) AS LOCEMAIL, sum(SHARE) AS LOCSHARE, now()
    FROM STAT
    WHERE ID = ".$id."
    GROUP BY MODEL;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM