2013-07-19 314 views
1

我的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 

表中有重複的行

OUTPUT我需要的是

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

OUTPUT我得到的是

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

這是真空的兩倍升計算

我想在這個計算中排除那些重複的行

,請給我一些暗示

+3

使用'DISTINCT'和子查詢。 –

+0

@BartFriederichs我應該使用DISTINCT選擇哪一列先生? – ManojGeek

+0

@ user2598438,您不必重複,唯一的字段。 – maximkou

回答

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演示

+0

+1 - 恥辱的數據是不夠的,它需要這種治療 – LoztInSpace

+0

簡單的非規範化,也許有些維度建模? – Whimusical

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" 
); 
+0

沒有輸出,使用GROUP BY我得到輸出在兩行中打印兩次,計算完成的是數學+數學和科學+科學科目 – ManojGeek