在写管家app的数据报表的时候,有一个数据,总是多一,在排查的时候本地自己写sql也觉得没问题,后来发先是坑在一个很小的点
有问题的sql
select
COUNT(distinct case when (receipt.receipt_create_time between '2024-01-09 00:00:00' and '2024-01-09 23:59:59') then receipt.receipt_inner_no else '' end)
from
receipt
where
receipt.system_book_code = 5302
and receipt.account_num in (99, 2, 1, 5302)
and receipt.receipt_type = 'POS前台'
and receipt.receipt_money > 0
and (receipt.receipt_status is null
or receipt.receipt_status <> -1)
and receipt.deleted = 0
and receipt.receipt_create_time between '2024-01-08 00:00:00' and '2024-01-09 23:59:59';
正确的sql
select
COUNT(distinct case when (receipt.receipt_create_time between '2024-01-09 00:00:00' and '2024-01-09 23:59:59') then receipt.receipt_inner_no end)
from
receipt
where
receipt.system_book_code = 5302
and receipt.account_num in (99, 2, 1, 5302)
and receipt.receipt_type = 'POS前台'
and receipt.receipt_money > 0
and (receipt.receipt_status is null
or receipt.receipt_status <> -1)
and receipt.deleted = 0
and receipt.receipt_create_time between '2024-01-08 00:00:00' and '2024-01-09 23:59:59';
- 第一个查询:
这个查询使用了 else ''
,即当日期条件不满足时,返回一个空字符串。这可能导致 COUNT(distinct ...)
函数对空字符串的计数,从而影响结果。
- 第二个查询:
这个查询没有 else
部分,因此在日期条件不满足时返回 NULL
(因为没有指定 else
时,case
语句的默认返回值为 NULL
)。COUNT(distinct ...)
函数通常会忽略 NULL
值,因此这种写法可能更符合期望。
总的来说,如果你想要确保只统计在日期范围内的 receipt_inner_no
,且不希望包括空字符串,第二个查询的写法更为合适。第一个查询的写法可能导致计数不准确,具体取决于你的数据。