总和不返回准确的值

时间:2014-01-21 18:36:03

标签: join sum sql-server-2012

我正在尝试编写查询,以了解每个固定时间段内有多少客户。这些期间已在数据库中设置,我只是在那段时间内对客户进行总结。

使用:

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 checknum
  • 0,2917
  • 1,2918
  • 1,2921
  • 1,2922
  • 2,2919
  • 2,2923
  • 3,2920

总结:

  • [生效日期]访客fixedperiod revenuecenterid
  • 2014-1-20,200,89,146708

预期结果:

  • [生效日期]访客fixedperiod revenuecenterid
  • 2014-1-20,10,89,146708

3 个答案:

答案 0 :(得分:0)

您是否尝试将过滤器放在括号中以避免混淆。

我认为“和fixedperiod = '89'”会带来更多记录。把这个陈述放在上面。

答案 1 :(得分:0)

我认为你的查询比你需要的要复杂得多。试试这个开始:

DECLARE @date DATE = '2014-01-20';

SELECT 
  [Effective Date] = m.businessdate, 
  guests = SUM(h.numguests), 
  h.fixedperiod, 
  h.revenuecenterid
FROM 
  dbo.MENU_ITEM_FIXED_PERIOD_TOTAL AS m
INNER JOIN dbo.guest_check_hist AS h
  ON h.openbusinessdate >= m.businessdate
  AND h.openbusinessdate < DATEADD(DAY, 1, m.businessdate)
  AND h.fixedperiod = m.fixedperiod
  AND h.revenuecenterid = m.revenuecenterid
WHERE m.businessdate = @date
GROUP BY m.businessdate, h.fixedperiod, h.revenuecenterid
ORDER BY h.fixedperiod;

SQL Fiddle demo

答案 2 :(得分:0)

我通过确定总和所需的所有数据都在guest_check_hist中并且总和以某种方式将总数加倍来解决这个问题。