mysql查询问题与计算字段

时间:2014-03-21 18:17:39

标签: mysql sql database

我想通过人工生成来选择客户交易。

它应该显示所有回叫,约会,发送电子邮件或特定代理人的任何其他状态(由id生成)。

架构:

CREATE TABLE IF NOT EXISTS `client_transaction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `client_id` int(11) NOT NULL,
  `generated_by_id` int(11) NOT NULL,
  `schedule_for_id` int(11) NOT NULL,
  `transaction_type` varchar(50) NOT NULL,
  `target_date_time` datetime NOT NULL,
  `date_added` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `client_id` (`client_id`)
)

查询:

SELECT generated_by_id as agent_id, count(*) as call_backs
FROM client_transaction
WHERE transaction_type='CALL_BACK'
GROUP BY generated_by_id

SQL FIDDLE

我已经为一个状态创建了查询。但是,我需要每个地位。我还想从其他代理表中获取代理名称。获取所有适当的数据后,如何与代理表保持联接?

感谢。

2 个答案:

答案 0 :(得分:1)

只需将transaction_type添加为查询中的字段,然后对其应用其他级别的分组:

SELECT
    generated_by_id AS agent_id,
    transaction_type,
    count(*) AS transaction_count
FROM client_transaction
GROUP BY generated_by_id, transaction_type
/* sort in some manner */
ORDER BY generated_by_id ASC, transaction_type ASC

使用与代理表的连接执行类似查询的示例可能如下所示:

SELECT
    /* I am assuming field names on agent table
     * and am guessing you want to join to be able
     * to get something like agent name in this query
    */
    a.id AS `agent_id`,
    a.name AS `agent_name`,
    ct.transaction_type AS `transaction_type`,
    count(*) AS `transaction_count`
FROM agent AS a
LEFT JOIN client_transaction AS ct
    ON a.id = ct.generated_by_id
GROUP BY `agent_id`, `transaction_type`
/* sort in some manner */
ORDER BY `agent_id` ASC, `transaction_type` ASC

答案 1 :(得分:0)

  

我需要每个状态

按交易类型分组。

SELECT generated_by_id as agent_id, transaction_type, count(*) as call_backs
FROM client_transaction
GROUP BY generated_by_id, transaction_type
  

我怎样才能与代理人表联系?

使用LEFT JOIN