MYSQL自行加入以选择去年的销售额

时间:2011-11-12 04:30:48

标签: mysql self-join

我正在尝试从一系列给定日期中选择历史总计(t1.date - 1)(t1.DATE> ='2011-01-01'和t1.DATE< ='2011 -11-11')

SELECT 
t1.date as DATE, SUM(t1.total), t2.date, sum(t2.total)
FROM T_SALES t1

LEFT OUTER JOIN T_SALES t2
on (t2.date = (t1.date - 1)
AND t2.rc = t1.rc
AND t2.storenum = t1.storenum)
WHERE 
    t1.RC = 0 
AND t1.STORENUM = '1,'
AND t1.DATE >= '2011-01-01' 
AND t1.DATE <= '2011-11-11' 
GROUP BY t1.date

ORDER BY t1.DATE ASC

我的第二个聚合t2.total是我的问题所在 - SUM(t1.total)表示准确的销售总额)

以下是我的输出

enter image description here

值27.90,应该是5.58 - 看起来我总结了总和(t2.total)。

按t1.total分组也显示:(5.58 * 5 = 27.90)

enter image description here

我已经尝试过所有可以想象到的分组,但是无法做到正确,有任何想法吗?谢谢大家!

3 个答案:

答案 0 :(得分:2)

您的问题是您在两个表之间获得半笛卡尔产品--T1表中的两个销售和T2表中的三个销售将在预聚合结果集中产生六行。

有两种方法可以解决这个问题:

  1. 首先汇总表格 ,然后将汇总表格加在一起。

  2. 将整个查询基于第一个表上的简单选择,并在结果中嵌套查询以获得第二个总数。

  3. 这是解决方案1(请注意,这是按RC(区域代码?)和storenum细分的,如果不是您想要的那么简单删除对这些列的所有引用):

    CREATE VIEW DailyTotals (RC, StoreNum, Date, TotalAmount) AS 
    SELECT RC, StoreNum, Date, SUM(Total) FROM T_Sales
    GROUP BY RC, StoreNum, Date
    
    SELECT TODAY.RC, TODAY.StoreNum, TODAY.Date, TODAY.TotalAmount, 
           YDAY.Date, YDAY.TotalAmount
    FROM DailyTotals TODAY 
       LEFT OUTER JOIN DailyTotals YDAY ON YDAY.Date = TODAY.Date-1
    WHERE TODAY.Date BETWEEN '2011-01-01' AND '2011-11-11'
    

    这里是解决方案2(同样是区域和商店细分,可以删除):

      SELECT RC, StoreNum, Date, SUM(Total), Date-1,
        (SELECT SUM(Total) FROM T_Sales YDAY WHERE 
         YDAY.RC = TODAY.RC AND YDAY.StoreNum = TODAY.StoreNum AND YDAY.Date = TODAY.Date-1)
      FROM T_Sales TODAY WHERE Date BETWEEN '2011-01-01' AND '2011-11-11'
    

答案 1 :(得分:1)

也许是次选?

select *
  from (
select sum(total)
     , date 
     , rc
     , storenum
 from T_SALES
group by date, rc, storenum)T1
left join(
select sum(total)
     , date 
     , rc
     , storenum
 from T_SALES
group by date, rc, storenum)T2
 on T2.date = (T1.date - 1)
and T2.storenum = T1.storenum

答案 2 :(得分:0)

尝试将您的查询修改为以下内容:

SELECT 
t1.date as DATE, SUM(t1.total), t1.date, sum(t1.total)
FROM T_SALES t1
WHERE 
    t1.RC = 0 
AND t1.STORENUM = '1,'
t1.date BETWEEN '2011-01-01' AND '2011-11-11' 
GROUP BY t1.date
ORDER BY t1.date ASC

您的别名t1和t2只是使用相同的表并再次进行计算。您之前的查询非常混乱。然后在where语句中添加您需要的条件,并在此处发布您再次执行的操作