2017-07-27 100 views
1

我已經看過了幾個不同的答案,這個問題似乎並不能得到查詢才能正常工作。Mysql的運行總​​計關閉一個表

這裏是我的表有列用戶,weekNo,salesTotalYTD。

我目前由周拉動這些出來,將它們分組,像這樣:

+------+--------+---------------+ 
| user | weekNo | salesTotalYTD | 
+------+--------+---------------+ 
|Jared | 1 |  200  | 
+------+--------+---------------+ 
| Jim | 1 |  50  | 
+------+--------+---------------+ 
|Jared | 2 |  30  | 
+------+--------+---------------+ 
| Jim | 2 |  100  | 
+------+--------+---------------+ 

我所試圖做的,但不能完成如下:

+------+--------+---------------+ 
| user | weekNo | salesTotalYTD | 
+------+--------+---------------+ 
|Jared | 1 |  200  | 
+------+--------+---------------+ 
| Jim | 1 |  50  | 
+------+--------+---------------+ 
|Jared | 2 |  230  | 
+------+--------+---------------+ 
| Jim | 2 |  150  | 
+------+--------+---------------+ 

這是查詢我已經工作了第一遍但之後每次傳球是錯誤的:

SET @runtot:=0 

SELECT 
    salesTotalYTD, 
    user, 
    (@runtot := @runtot + salesTotalYTD) AS rt 
    FROM weeksAndSalesmantbl 
    GROUP BY user, weekNo 
    ORDER BY (CASE WHEN weekNo = 52 THEN 0 ELSE 1 END) ASC, weekNo, user ASC 

更新

添但返回錯誤的更新代碼禮貌:

$assignments = " 
    SELECT 
    t1.user, 
    t1.weekNo, 
    (SELECT SUM(t2.salesTotalYTD) FROM weeksAndSalesmantbl t2 
    WHERE t2.user = t1.user AND t2.weekNo <= t1.weekNo) AS salesTotalYTD 
    FROM weeksAndSalesmantbl t1 
    ORDER BY 
    t1.weekNo, 
    t1.user"; 

    $salesTotalSalesManCumulative = []; 

    $assignmentsqry = mysqli_query($db,$assignments); 

    if (!$assignmentsqry) { 
    printf("Error: %s\n", mysqli_error($db)); 
    exit(); 
    } 

    while ($row = mysqli_fetch_array($assignmentsqry)) { 

    $float = floatval($row['salesTotalYTD']); 
    $float = round($float,2); 

    array_push($salesTotalSalesManCumulative,$float); 

    } 
+0

你真的有'SELECT'出現兩次這樣呢? –

+0

不,這是一個小姐副本,我糾正它。 –

+1

我已提高您的問題。我們需要一個PHP人來看待這個問題並提出意見。我認爲你使用會話變量的原始方法也很好。 –

回答

3

爲此,可以使用標準的運行總計查詢方法。但是,在這種情況下,我們也會將總和限制在特定的用戶。

SELECT 
    t1.user, 
    t1.weekNo, 
    (SELECT SUM(t2.salesTotalYTD) FROM weeksAndSalesmantbl t2 
    WHERE t2.user = t1.user AND t2.weekNo <= t1.weekNo) AS salesTotalYTD 
FROM weeksAndSalesmantbl t1 
ORDER BY 
    t1.weekNo, 
    t1.user 

輸出:

enter image description here

演示在這裏:

Rextester

更新:

自從你告訴我們,weeksAndSalesmantbl是一個臨時表,和MySQL不喜歡我上面給查詢遊戲後期,可以考慮使用單傳過來的表會話變量。

SET @rt = NULL; 
SET @user = NULL; 

SELECT 
    t.user, 
    t.weekNo, 
    t.rt AS salesTotalYTD 
FROM 
(
    SELECT 
     @rt:=CASE WHEN @user=user THEN @rt+salesTotalYTD ELSE salesTotalYTD END AS rt, 
     @user:=user AS user, 
     weekNo 
    FROM weeksAndSalesmantbl 
    ORDER BY 
     user, 
     weekNo 
) t 
ORDER BY 
    t.weekNo, 
    t.user; 

Demo

如果這仍然給你的錯誤,那麼你可能要考慮擺脫該臨時表。無論如何,你可能不想在生產中使用臨時表。

+0

提供的鏈接上發生的:'警告:mysqli_fetch_array()預計參數1被mysqli_result' –

+0

@CraigHowell我查詢工作,qv演示。如果你還有其他問題,也許你在PHP代碼中做了一些不正確的事情。 –

+0

我會用PHP發佈我的完整代碼。在與代碼交換之前它正常運行。 –