SQL如何从上个月的分组依据中获取值以在当前分组依据中使用?

时间:2018-09-29 17:47:56

标签: sql

如何在同一行中获得今年的线索数和去年的线索数。我需要的查询更加复杂,但这是第一步。

输出

Year,Count,Last Year Count
2016,55,88
2017,77,55
2018,83,77

SELECT L1.Year, count(L1.LeadId), count(Lead_Last_Year.Lead_count) from Leads
???
Group by Year

谢谢

3 个答案:

答案 0 :(得分:1)

您可以尝试退出加入分组子查询。

SELECT x.year,
       x.count,
       y.count last_year_count
       FROM (SELECT l1.year,
                    count(l1.leadid) count
                    FROM leads l1
                    GROUP BY l1.year) x
            LEFT JOIN (SELECT l1.year,
                              count(l1.leadid) count
                              FROM leads l1
                              GROUP BY l1.year) y
                      ON y.year = x.year - 1;

如果您的DBMS支持CTE,您还可以使用CTE代替重复出现的子查询。

WITH cte
AS
(
SELECT l1.year,
       count(l1.leadid) count
       FROM leads l1
       GROUP BY l1.year
)
SELECT x.year,
       x.count,
       y.count last_year_count
       FROM cte x
            LEFT JOIN cte y
                      ON y.year = x.year - 1;

答案 1 :(得分:0)

您可以对第一次选择的结果进行联接。因此,您可以这样做:

SELECT 
   L1.Year,
   count(L1.LeadId), 
   count(L2.LeadId) 
FROM Leads L1
LEFT JOIN Leads L2 on L1.Year = L2.Year+1
Group by Year

答案 2 :(得分:0)

使用ISO / ANSI标准LAG()函数:

SELECT l.Year, count(*),
       LAG(COUNT(*)) OVER (ORDER BY l.YEAR) as prev_year
FROM Leads l
GROUP BY l.Year;

与其他方法相比,该方法应具有最佳性能。