获取有关客户总访问量和收入的数据

时间:2014-03-31 10:05:19

标签: php mysql sql

我有两个表,tbl_customers和tbl_transactions,其中的字段如下:

**tbl_customer:**

c_id  |  c_name  |  age  |  Slab  |  gender  |  occupation  |  married  |  priority  |  ratings  |  contact  |  email  |  dob  |  anniversary

**tbl_transaction**


t_id  |  c_id  |  d_id  |  f_id  |  date_time  |  bill  |  member

tbl_transaction 是一个全局表,其中包含所有部门的交易,区别为 d_id

现在我想运行一个提取 c_id 总访问次数的查询(表示tbl_transaction中c_id apppears的行数没有),总收入(表示特定c_id in的SUM(bill))以及tbl_customer中的相应优先级和评级。

我正在尝试的查询是:

Select c_id,
COUNT(cid) as tot_visit,
SUM(bill) as tot_revenue, priority, ratings 
From tbl_customer c
inner join tbl_transaction t on c.c_id=t.c_id
Where $r_id='r1' AND $c_id='".$cid."'
group by c_id

所以我基本上想要在客户表中显示每个客户的总访问量和收入,但不确定这样做的正确方法。

任何帮助都将不胜感激。

This is the error I am getting in SQL Engine 这是我在SQL Engine中得到的错误

2 个答案:

答案 0 :(得分:1)

根据您的错误,两个表中的字段在您的表中具有相同的名称,您需要为该字段提供表别名,当您仅对一个组进行过滤时,则不需要使用group by,因为您正在将AND c.c_id='".$cid."'用于单个群组

Select c.c_id,
COUNT(c.cid) as tot_visit,
SUM(t.bill) as tot_revenue, c.priority, c.ratings 
From tbl_customer c
inner join tbl_transaction t on c.c_id=t.c_id
Where $r_id='r1' AND c.c_id='".$cid."'
group by c.c_id

答案 1 :(得分:0)

一般情况下,查询很好。我会用内部替换内部联接来处理客户没有交易

Select c_id, COUNT(cid) as tot_visit, SUM(bill) as tot_revenue, 
       priority, ratings 
From tbl_customer c LEFT JOIN tbl_transaction t on c.c_id=t.c_id 
Where $r_id='r1' AND $c_id='".$cid."' 
group by c_id