2012-07-27 67 views
0

我有一個表門票(用戶名,職位,方案) 用戶可能有可能的職位。 用於例如,查詢在SQL笨

____________________________________ 
username | posts | scheme | 
__________|____________|___________| 
A   | post1 |  10 | 
__________|____________|___________| 
B   | post2 |  2 | 
__________|____________|___________| 
B   | post 3 |  13 | 
__________|____________|___________| 
A   | post 4 |  21 | 
__________|____________|___________| 
A   | post 5 |  -1 | 
__________|____________|___________| 

我的查詢應該geneate加標題,總聲望的總數輸出不同的用戶名。即,

_______________________ 
|A | 3 | 30 | 
|____|_______|_________| 
|B | 2 | 15 | 
|____|_______|_________| 

我的模型功能: -

function getAllUsers(){      
     $this->db->distinct(); 
     $this->db->select('username,COUNT(title) AS numtitle'); 
     $this->db->where('site_referers_id',1); 
     return $this->db->get('tbl_tickets'); 
    } 

但似乎沒有工作:(

+3

您必須使用group by。 – 2012-07-27 08:02:23

+0

您還需要按用戶名進行分組,'$ this-> db-> group_by('username');' – Gavin 2012-07-27 08:02:42

回答

4

您應該使用$this->db->group_by()而不是distinct

function getAllUsers(){      
    $this->db->select('username, COUNT(*) AS numtitle, SUM(scheme) AS total'); 
    $this->db->where('site_referers_id',1); 
    $this->db->group_by('username'); 
    return $this->db->get('tbl_tickets'); 
} 
2

檢查這代碼

$this->db->select('username,COUNT(title) AS numtitle'); 
    $this->db->where('site_referers_id',1); 
    $this->db->group_by('username'); 
    return $this->db->get('tbl_tickets'); 

您獲得完美的結果

0

我知道這個問題問很前,但舊的答案得不到重視的作者。 嘗試使用SQL:

$sql ="SELECT count(*),username,SUM(scheme) FROM `tble_one` group by username"; 
$result = $this->db->query($sql)->get();