简体   繁体   English

同一查询中的DISTINCT计数和总和

[英]DISTINCT count and sum in the same query

this is my table 这是我的桌子

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

i have a query that gives me the stats of the table based on the agency ,basically couple of counts and sums 我有一个查询,该查询根据代理机构为我提供表格的统计信息,基本上是几个计数和总和

 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

but i want rows with the same ticket_id to be counted only once 但我希望具有相同ticket_id的行仅被计数一次

for example the first two row have the same ticket id and they are actually one ticket . 例如,前两行具有相同的票证ID,实际上它们是一张票证。

i can do this for the total count 我可以做到这一点的总数

 SELECT  COUNT(distinct(ticket_id)) as total , 

i'm not sure how to do this for the SUM ? 我不确定如何对SUM执行此操作? i know this doesn't works 我知道这行不通

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

Well, if you need only one result row: 好吧,如果您只需要一个结果行:

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 http://www.sqlfiddle.com/#!2/cde84/1

Note that this assumes that two different agencies will not share a ticket_id. 请注意,这假设两个不同的代理机构不会共享ticket_id。

Edit. 编辑。 Well, I reread your post, and I'm not sure if you want the TOTAL number of rows in the table or just the unique ticket ids. 好吧,我重新阅读了您的文章,并且不确定是否要表中的总行数或仅要使用唯一的凭单ID。 If you just want the unique ticket ids then you can do: 如果您只想要唯一的票证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;

See: http://www.sqlfiddle.com/#!2/cde84/5 请参阅: http//www.sqlfiddle.com/#!2 / cde84 / 5

I would say use 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM