Mysql计数按组发生为列值

时间:2014-10-30 22:57:22

标签: mysql sql find-occurrences

我做了以下查询:

select ba_brand, ceil(sum((sk_front + sk_depth + sk_warehouse + (sk_exhibition  IS NOT NULL))) / count(distinct(vi_pdv_id_pdv))) as 'inventory',
count(vi_pdv_id_pdv)
from sf_visit_stock

join sf_visit on sk_vi_id_visit = id_visit
join sf_pdv on vi_pdv_id_pdv = id_pdv
join sf_format on pdv_fo_id_format = id_format
join sf_group on fo_gr_id_group = id_group
join sf_channel on gr_ch_id_channel = id_channel

join sf_product on sk_pd_id_product = id_product
join sf_family on pd_fa_id_family = id_family
join sf_brand on fa_ba_id_brand = id_brand

where (CASE WHEN from_unixtime(vi_scheduled_start,'%Y-%m-%d') between '2014-10-01' and '2014-10-31' AND vi_vs_id_visit_status in (1,2,3,4,6) THEN 4 END)
and vi_pr_id_proyect = 5 and ba_rival = 0 and id_brand in (72,75,76,77,78,79,80)
and sf_channel.ch_channel not in ("CHAINS DIRECTS", "CHAINS INDIRECTS", "INDEPENDENTS", "SUPERMARKET")

group by ba_brand

换句话说,我正在做一些sum()的某些值:

sum((sk_front + sk_depth + sk_warehouse + (sk_exhibition  IS NOT NULL))

从多行开始:

count(vi_pdv_id_pdv)

但这些行中的ID是重复的,因此count(vi_pdv_id_pdv)会返回一个计算所有重复ID的值。 我希望得到vi_pdv_id_pdv的值而不重复。这是一个小例子。通过此查询,我得到以下结果:

My Product |    32031 | 1098

在此示例中,1098计算重复值。而且我想得到:

My Product |    32031 | 534

该计数没有重复的值。 我知道group by语句无需重复,如this answer我读过, 但是我无法实现类似于我在上面显示的查询中的内容...

有人可以帮帮我吗?

感谢!!!

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

重复项来自哪里?

我认为它们是由您的一个连接引起的。您可以在此联接中添加其他子句以摆脱它们。示例:

SELECT *
FROM sf_visit_stock AS vs
JOIN sf_visit AS v ON vs.sk_vi_id_visit = v.id_visit AND v.somevalue = 1

在WHERE子句中也有可能摆脱它们。