我正在构建一个数据库报告,我需要确定按公司,工作和日期分组的“第一次扫描”的数量。
扫描表可以包含同一项目的多次扫描,但是我只想在我的COUNT中包含原始扫描,这只能被识别为具有与特定项目匹配的最早日期的扫描。
我的第一次尝试是:
SELECT
_item_detail.job_id,
_item_group.group_id,
_scan.company_id,
DATE(scan_date_time) as scan_date,
COUNT(1)
FROM _scan
INNER JOIN _item_detail ON _item_detail.company_id = _scan.company_id
AND
_item_detail.serial_number = _scan.serial_number
INNER JOIN _item_group ON _item_group.group_id = _item_detail.group_id
WHERE _item_detail.job_id = '0326FCM' AND _scan.company_id = '152345' AND _item_group.group_id = 13
GROUP BY
_item_detail.job_id,
_item_group.group_id,
_scan.company_id, scan_date -- first_scan_count
HAVING min(scan_date_time);
这给了我不正确的结果(约3倍太多)。我假设这是因为每个日期都会重新计算MIN记录,所以如果在第1天找到分钟,也可以在第3天找到它并重新计算。
如何修改查询以达到预期效果?
答案 0 :(得分:2)
类似的东西应该有效...我不完全确定你的表格如何布局或数据如何将它们联系在一起,但这是一般的想法:
SELECT
_item_detail.job_id,
_item_group.group_id,
_scan.company_id,
DATE(scan_date_time) as scan_date,
COUNT(1)
FROM
_scan s1
INNER JOIN _item_detail
ON _item_detail.company_id = s1.company_id
AND _item_detail.serial_number = s1.serial_number
AND _item_detail.job_id = '0326FCM'
INNER JOIN _item_group
ON _item_group.group_id = _item_detail.group_id
AND _item_group.group_id = 13
WHERE
s1.company_id = '152345'
AND s1.scan_date_time = (
SELECT MIN(s2.scan_date_time)
FROM _scan s2
WHERE
s2.company_id = s1.company_id
AND s2.serial_number = s1.serial_number
)
GROUP BY
_item_detail.job_id,
_item_group.group_id,
s1.company_id
答案 1 :(得分:0)
我不太关注你的查询,但根据问题的描述,我会说创建一个子查询,给出每个项目的最小扫描日期,按项目分组,执行你的外部选择