如何根据一定条件计算总和

时间:2019-09-25 04:55:46

标签: php mysql sum

我想根据用户名计算培训时间的总和。但是,当我使用函数SUM()时,它将显示数据库中所有培训时间的总计。谁能帮我吗?

<?php
    include('session.php');
    include_once('DB_connect.php');

    $UID = $_SESSION['USERID'];
    if(isset($_POST["USER_NAME"])){
        $B_title  = strtoupper($_POST["USER_NAME"]);
        $sql = "SELECT 
                TS_ID, TS_DATE, TS_DDATE, TS_HOUR, 
                TRAINING_NAME,TRAINING_HOUR, USER_NAME, 
                SUM(B.TRAINING_HOUR) AS TOTAL

            FROM 
                TRAINING_STATUS TS,
                USER_INFO UI,
                TRAINING B
            WHERE
                TS.TRAINING_ID = B.TRAINING_ID
            AND
                TS.USER_ID = UI.USER_ID
            ";

        include('sql.php');

        if(mysql_num_rows($retval) > 0){}
             print   '<table  align="right" style="width:14%">
                            <tr style="background-color:1AB299">
                                <th>TOTAL TRAINING HOUR </th>
                            </tr>';

                while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
                    print "<tr style='background-color:BCF9EF'>
                                <th>{$row['TOTAL']}</th>
                            </tr>";
                }
    }
?>

1 个答案:

答案 0 :(得分:-2)

詹姆斯指出!

将查询更改为:

-- Shared row variable for caching config data. Declared at Global scope.
DECLARE S_ConfigSharedRow SHARED ROW;

CREATE COMPUTE MODULE TheFirstComputeNode
CREATE FUNCTION Main() RETURNS BOOLEAN
BEGIN
    CFGDATA_CACHE_LOCK: BEGIN ATOMIC
        -- If the configuration data is not available in the cache then load it from the CONFIG table
        DECLARE CfgDataRef REFERENCE TO S_ConfigSharedRow.CfgDataCache;
        IF NOT LASTMOVE(CfgDataRef) THEN
            -- Select all the relevant content from the actual database in one go.
            DECLARE DBResults ROW;
            DECLARE RetryCount INTEGER 5;
            SET DBResults.Row[] = PASSTHRU('SELECT * FROM CONFIG');

            -- Typically you would post process the content from the DB into a more amenable 
            -- structure but the following will get the data into the shared variable
            CREATE LASTCHILD OF S_ConfigSharedRow.CfgDataCache FROM DBResults;
        END IF;
    END CFGDATA_CACHE_LOCK;

    -- Config data is now available for use

    RETURN TRUE;
END;
END MODULE;