MYSQL计算避免重复值

时间:2013-07-19 07:43:13

标签: php mysql

我的MySQL表是

 htno     name       fathername       subcode      subject       internals     externals     total    result      tempcr
 12      Mahesh        Rajesh           256         Maths           20            55           75        P           1
 12      Mahesh        Rajesh           257        Science          18            60           78        P           1
 12      Mahesh        Rajesh           256         Maths           20            55           75        P           1
 12      Mahesh        Rajesh           257        Science          18            60           78        P           1

表格有重复的行

我需要的输出是

HTNO     TOTAL MARKS SECURED       PERCENTAGE       TOTAL SUBJECTS       SUBJECTS ATTEMPTED      SUBJECTS ABSENT         SUBJECTS PASSED        BACKLOGS
12               153                   76.5%             2                      2                       0                    2                       0

我得到的输出是

HTNO     TOTAL MARKS SECURED       PERCENTAGE       TOTAL SUBJECTS       SUBJECTS ATTEMPTED      SUBJECTS ABSENT         SUBJECTS PASSED        BACKLOGS
12               306                   153%              4                      4                       0                    4                       0

这是实际计算的两倍

我想在此计算中排除那些重复的行

请给我一些提示

2 个答案:

答案 0 :(得分:4)

尝试

SELECT htno, 
       SUM(total)               tech, 
       ROUND(SUM(total) / 2, 2) divi, 
       SUM(tempcr)              cred, 
       SUM(tempcr <= 0)         log,
       SUM(tempcr >  0)         pass, 
       SUM(externals >= 0)      atm, 
       SUM(externals <  0)      tot
  FROM 
( 
  SELECT DISTINCT * 
    FROM Table1 
   WHERE htno = 12
) q

输出:

| HTNO | TECH | DIVI | CRED | LOG | PASS | ATM | TOT |
------------------------------------------------------
|   12 |  153 | 76.5 |    2 |   0 |    2 |   2 |   0 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

使用GROUP_BY或DISTINCT:

$sum = $db->prepare("
    SELECT htno, 
    SUM(total) AS tech, 
    ROUND(SUM(total)/7.5, 2) AS divi, 
    SUM(tempcr) AS cred, 
    SUM(CASE WHEN tempcr <= 0 THEN 1 ELSE 0 END) AS log,
    SUM(CASE WHEN tempcr > 0 THEN 1 ELSE 0 END) AS pass, 
    SUM(CASE WHEN externals >= 0 THEN 1 ELSE 0 END) AS atm, 
    SUM(CASE WHEN externals >= -2 THEN 1 ELSE 0 END) AS tot 
    FROM btech32r09july2013 
    WHERE htno = :id 
    GROUP_BY subject"
);