如何获取当前和去年的信息

时间:2019-12-16 22:55:23

标签: mysql sql join

我有下表。如果某一天没有潜在客户,则不会输入任何数据。

Date        Center      Leads
1/1/2018    A           2
1/1/2018    B           1
1/2/2018    A           2
1/3/2018    A           4
1/3/2018    B           1
1/1/2019    A           3
1/3/2019    A           2

当我参加会议时,我希望按中心获得今年和去年的潜在客户。另外,如果今年没有潜在客户,但去年有条目,我想将今年包括在结果集中为0。

结果集:

Date        Center      Leads     Leads-PastYear
1/1/2018    A           2         0
1/1/2018    B           1         0
1/2/2018    A           2         0
1/3/2018    A           4         0
1/3/2018    B           1         0
1/1/2019    A           3         2
1/1/2019    B           0         1
1/2/2019    A           0         2
1/3/2019    A           2         4
1/3/2019    B           0         1

我的查询:

SELECT 
  T1.Date, 
  T1.Center, 
  T1.Leads, 
  T2.Leads AS 'Leads-PastYear' 
FROM table T1
LEFT JOIN table T2 ON 
  DATE_SUB(T1.Date, INTERVAL 1 YEAR) = T2.Date AND
  T1.Center = T2.Center

UNION ALL 

SELECT 
  DATE_ADD(T2.Date, INTERVAL 1 YEAR) AS 'Date', 
  T2.Center, 
  T1.Leads, 
  T2.Leads AS 'Leads-PastYear' 
FROM table T1
RIGHT JOIN table T2 ON 
  DATE_ADD(T2.DATE, INTERVAL 1 YEAR) = T1.Date AND
  T2.Center = T1.Center
WHERE DATE_ADD(T2.Date, INTERVAL 1 YEAR) NOT IN (SELECT T3.Date FROM table T3) AND 
YEAR(DATE_ADD(T2.Date, INTERVAL 1 YEAR)) <= YEAR(CURRENT_DATE)

2 个答案:

答案 0 :(得分:0)

我正在考虑获取结果集中的所有日期,然后使用JOIN来获取两年中的日期:

with dc as (
      select t.date, t.center
      from t
      where t.date >= datefromparts(year(getdate() - 1, 1, 1)
      union   -- on purpose to remove duplicates
      select dateadd(year, 1, t.date), t.center
      from t
      where t.date >= datefromparts(year(getdate() - 1, 1, 1) and
            t.date < datefromparts(year(getdate(), 1, 1)
     )
select dc.date, dc.center, t.leads,
       coalesce(tprev.leads, 0) as prev_year_leads
from dc left join
     t
     on t.date = dates.date and t.center = dc.center left join
     t tprev
     on tprev.date = dateadd(year, -1, dates.date) and
        tprev.center = dc.center;

我对使用窗口函数有些警惕。 years年可能会引起问题。

答案 1 :(得分:0)

SELECT
  T2.Date,
  T2.Center,
  SUM(T2.Leads),
  SUM(T2.Leads2)
FROM (
    SELECT 
      T1.Date AS Date,
      T1.Center AS Center,
      T1.Leads As Leads,
      0 AS Leads2
    FROM table T1

    UNION

    SELECT
      DATE_ADD(T1.Date, INTERVAL 1 YEAR) AS Date,
      T1.Center AS Center,
      0 AS Leads,
      T1.Leads AS Leads2
    FROM table T1
) AS T2

GROUP BY T2.Date, T2.Center