如何计算MySql中的唯一和重复
我在下面提到了两个表: 表1如何计算MySql中的唯一和重复,mysql,Mysql,我在下面提到了两个表: 表1 ID Value RS-1 10 RS-2 20 RS-6 30 RS-3 40 表2 ID2 Ref_ID status Date RS-1 se12tc accepted 2019-01-01 14:06:46 RS-1 se14xc pending 2019-01-02 18:11:26 RS-1 se01df
ID Value
RS-1 10
RS-2 20
RS-6 30
RS-3 40
表2
ID2 Ref_ID status Date
RS-1 se12tc accepted 2019-01-01 14:06:46
RS-1 se14xc pending 2019-01-02 18:11:26
RS-1 se01df shipped 2019-01-01 13:16:34
RS-6 se73zc reject 2019-01-03 11:19:20
RS-6 sy01tc pending 2019-01-03 19:17:16
RS-2 se56vc accepted 2019-02-02 10:06:02
RS-2 se00tc reject 2019-02-02 12:02:16
RS-2 se88ee pending 2019-02-03 12:23:47
RS-3 se13xf accepted 2019-01-01 18:36:11
通过利用以上两个表,我需要导出格式中提到的输出
在哪里,
-源自月
列日期
-表2中针对 相同的Distinct\u ID>1计数
月份
-发生次数超过1次的Total\u ID>1count
总数的总和 表2中的时间为同一ID
月份的时间
-表2中仅出现一次的1count
的总和 相同的ID
月份
Month Distinct_ID>1count Total_ID>1count 1count Sum_Value
Jan-2019 2 5 1 50
Feb-2019 1 3 0 50
首先按月份和id2分组以获取每个id2的计数,然后使用条件聚合:
select
t.month,
sum(t.counter > 1) `Distinct_ID>1count`,
sum(case when t.counter > 1 then counter else 0 end) `Total_ID>1count`,
sum(t.counter = 1) `1count`
from (
select
date_format(date, '%Y%m') morder,
date_format(date, '%b-%Y') month,
id2,
count(*) counter
from table2
group by morder, month, id2
)t
group by t.morder, t.month
order by t.morder
请参阅。结果:
首先按月份和id2分组以获取每个id2的计数,然后使用条件聚合:
select
t.month,
sum(t.counter > 1) `Distinct_ID>1count`,
sum(case when t.counter > 1 then counter else 0 end) `Total_ID>1count`,
sum(t.counter = 1) `1count`
from (
select
date_format(date, '%Y%m') morder,
date_format(date, '%b-%Y') month,
id2,
count(*) counter
from table2
group by morder, month, id2
)t
group by t.morder, t.month
order by t.morder
请参阅。结果:
谢谢,很抱歉,我没有添加要连接这两个表的
值
部分,请帮助我了解将连接条件放在何处以获得输出中的值。这回答了您发布时的问题。如果有新需求,请发布新问题。@user9211845请记住count(*)
countsNULL
值。。从示例数据和预期结果来看,不清楚您是否需要COUNT(*)
或COUNT()
来不计算NULL
值。谢谢,很抱歉,我没有添加要连接这两个表的值部分,请帮助我理解我应该将连接条件放在哪里才能在输出中获得值。这回答了您发布时的问题。如果有新需求,请发布新问题。@user9211845请记住count(*)
countsNULL
值。。从示例数据和预期结果来看,不清楚您是否需要COUNT(*)
或COUNT()
不计算NULL
值。。