【发布时间】:2014-01-21 18:36:03
【问题描述】:
我正在尝试编写一个查询来了解我在固定时间段内拥有多少客户。期间已在数据库中设置,我只是对该期间的客户进行总和。
使用:
select distinct numguests, checknum
from guest_check_hist
where revenuecenterid in ('146708') and openfixedperiod = '89'
and openbusinessdate between dateAdd(day, -2,getDate()) and dateAdd(day, -1,getDate())`
我发现我有 7 个订单,总共 10 个客户。
然后我运行:
Select Distinct MENU_ITEM_FIXED_PERIOD_TOTAL.businessDate as 'Effective Date',
sum(H.guests) as guests, menu_item_fixed_period_total.fixedperiod,
menu_item_fixed_period_total.revenuecenterid
FROM MENU_ITEM_FIXED_PERIOD_TOTAL
inner JOIN (
select distinct checknum, numguests as guests, openbusinessdate, revenuecenterid, openfixedperiod
from guest_check_hist
where openbusinessdate between dateAdd(day, -2,getDate()) and dateAdd(day, -1,getDate())
) H ON Menu_item_fixed_period_total.businessdate = H.openbusinessdate and menu_item_fixed_period_total.revenuecenterid = H.revenuecenterid and H.openfixedperiod = menu_item_fixed_period_total.fixedperiod
where menu_item_fixed_period_total.revenuecenterid in ('146708')
and menu_item_fixed_period_total.businessdate between dateAdd(day, -2,getDate()) and
dateAdd(day, -1,getDate()) and fixedperiod = '89'
group by fixedperiod, businessdate, menu_item_fixed_period_total.revenuecenterid
order by fixedperiod`
发现我有 200 位客人。
显然这是不对的。
Numguests 的数据类型为 Int。你能指出我的错误在哪里吗?
实际数据:
个别订单:
- numguets 校验码
- 0, 2917
- 1, 2918
- 1, 2921
- 1, 2922
- 2, 2919
- 2, 2923
- 3, 2920
汇总结果:
- [生效日期]客人固定期间收入中心ID
- 2014-1-20, 200, 89, 146708
预期结果:
- [生效日期]客人固定期间收入中心ID
- 2014-1-20, 10, 89, 146708
【问题讨论】:
-
为什么有 distinct 和 group by?你能展示一些样本数据和期望的结果吗?由于您过度使用 distinct,我几乎预计会比您更多的行。
-
Distinct 只是从我的故障排除中继承而来,以识别特定订单,因为没有它,它们会多次出现。由于求和而使用分组依据。
-
哦,请不要在评论中发布一堆数据。将示例数据添加到问题中或在SQL Fiddle 中正确准备。
-
问题底部有数据。
-
是否只有与过滤器匹配的数据(例如,落在 where 子句中的 openbusinessdate 范围内)?您预期的总和结果是什么?
标签: join sum sql-server-2012