Mysql 在SQL中按列顺序提取每月潜在客户计数?

Mysql 在SQL中按列顺序提取每月潜在客户计数?,mysql,mariadb,pivot-table,Mysql,Mariadb,Pivot Table,我正试图统计每个公司每月的潜在客户数量。我可以通过以下查询在任何一个月进行查询: MONTH 1 LEAD COUNTS select l.companyProfileID, count(l.id) as 'Month 1 LC' from lead l join companyProfile cp on cp.id = l.companyProfileID where l.createTimestamp between cp.createTimestamp and date_sub(cp.cr

我正试图统计每个公司每月的潜在客户数量。我可以通过以下查询在任何一个月进行查询:

MONTH 1 LEAD COUNTS
select l.companyProfileID, count(l.id) as 'Month 1 LC'
from lead l
join companyProfile cp on cp.id = l.companyProfileID
where l.createTimestamp between cp.createTimestamp and date_sub(cp.createTimestamp, INTERVAL -1 month)
group by companyProfileID

MONTH 2 LEAD COUNTS
select l.companyProfileID, count(l.id) as 'Month 2 LC'
from lead l
join companyProfile cp on cp.id = l.companyProfileID
where l.createTimestamp between date_sub(cp.createTimestamp, INTERVAL -1 month) and date_sub(cp.createTimestamp, INTERVAL -2 month)
group by companyProfileID
但我不想运行12个不同的查询来获得一年的潜在客户数量,而是想生成一个包含列的表:companyProfileID、month1lc、month2lc等等

我想这可能需要一个嵌入式select函数,但我仍在学习SQL。如何实现这一点?

您可以使用“条件聚合”,而不是运行多个查询。实际上,您将当前where条件移动到聚合函数中,以形成一个
大小写表达式
。请注意,
count()
函数忽略空值

select 
        l.companyProfileID
      , count(case when l.createTimestamp between cp.createTimestamp 
                    and date_sub(cp.createTimestamp, INTERVAL -1 month) then 1 end) as 'Month 1 LC'
      , count(case when l.createTimestamp between date_sub(cp.createTimestamp, INTERVAL -1 month)
                    and date_sub(cp.createTimestamp, INTERVAL -2 month) then 1 end) as 'Month 2 LC'

      ... more (similar to the above)

      , count(case when l.createTimestamp between date_sub(cp.createTimestamp, INTERVAL -11 month)
                    and date_sub(cp.createTimestamp, INTERVAL -12 month) then 1 end) as 'Month 12 LC'
from lead l
join companyProfile cp on cp.id = l.companyProfileID
where l.createTimestamp between cp.createTimestamp and date_sub(cp.createTimestamp, INTERVAL -12 month)
group by companyProfileID
还请注意,“介于”要求第一个日期早于第二个日期,例如,以下内容不会返回行:

select * from t where datecol between 2018-01-01 and 2017-01-01
然而,这将起作用:

select * from t where datecol between 2017-01-01 and 2018-01-01

使用
分组依据执行单个查询,以获得12组值。然后“透视”数据(通过另一个查询)以获得12列。跟随我添加的标签。