Postgresql在多列中计数

时间:2014-02-17 12:59:53

标签: postgresql

我正在尝试检索多行的count(*)函数。我使用以下查询

select distinct agent, count(customer) as total_customer, 
(select count(january_1) from salestable where january_1!=0 group by agent) as sales_customer
from salestable 
where customer_type = "urban"
group by agent 
order by agent asc

首先,我检索了不同的代理人编号,然后计算他有多少客户。请注意,没有客户的代理商很少。总不同代理是2000.但是在计数中它检索1600,因为400代理没有客户。在另一个名为january_1的专栏中,我有销售价值。我想得到一个表格,其中3列将列出不同的代理商,总客户数和总销售额。在1月1日,第0列表示没有销售。它应该看起来像

| Agent | Customer | Service | Served
| Lynda | 6 | 4 | 0
| Marks  | 7 | 5 | 6
| Tomas | 6 | 3 | 2

但结果我收到以下错误

more than one row returned by a subquery used as an expression

我必须做什么?

1 个答案:

答案 0 :(得分:0)

我不完全确定,但认为这就是你想要的

select agent, 
       count(customer) as total_customer, 
       count(case when january_1 <> 0 then 1 end)  as sales_customer
from salestable 
where customer_type = "urban"
group by agent 
order by agent asc