1

这是我的桌子

id , tiket_id , agency , problem
 1  , 123     , 1      ,  x
 2  , 123     , 1      ,  y
 3  , 124     , 2      ,  z

我有一个查询,它根据代理向我提供表格的统计信息,基本上是几个计数和总和

 SELECT  COUNT(*) as total , 
 SUM(CASE WHEN `agancy` = '1' THEN 1 ELSE 0 END) as ag_1
 SUM(CASE WHEN `agancy` = '2' THEN 1 ELSE 0 END) as ag_2

但我希望具有相同ticket_id 的行只计算一次

例如,前两行具有相同的票号,它们实际上是一张票。

我可以为总数做到这一点

 SELECT  COUNT(distinct(ticket_id)) as total , 

我不知道该怎么做SUM?我知道这行不通

 SUM(  DISTINCT ticket_id CASE WHEN `agancy` = '1' THEN 1 ELSE 0 END) as ag_1
4

2 回答 2

1

好吧,如果您只需要一个结果行:

select sum(cnt) as total, SUM(case when agency = 1 then 1 else 0 end) as ag1, SUM(case when agency = 2 then 1 else 0 end) as ag2 from (     
    SELECT COUNT(*) as cnt, agency
    from foo
    group by tiket_id,agency
) b

http://www.sqlfiddle.com/#!2/cde84/1

请注意,这假设两个不同的机构不会共享一个ticket_id。

编辑。好吧,我重读了你的帖子,我不确定你是想要表中的总行数还是只需要唯一的票证 ID。如果您只想要唯一的票证 ID,那么您可以执行以下操作:

select COUNT(*) as total , SUM(case when agency = 1 then 1 else 0 end) as ag1, SUM(case when agency = 2 then 1 else 0 end) as ag2 from (        
    SELECT COUNT(*) as cnt, agency
    from foo
    group by tiket_id,agency
) b;

见:http ://www.sqlfiddle.com/#!2/cde84/5

于 2012-11-17T20:38:14.803 回答
0

我会说使用 group by

SELECT  COUNT(*) as total , 
SUM(CASE WHEN `agancy` = '1' THEN 1 ELSE 0 END) as ag_1
SUM(CASE WHEN `agancy` = '2' THEN 1 ELSE 0 END) as ag_2
from mytable
group by tiket_id
于 2012-11-17T20:25:36.833 回答