我有一个查询,它会返回客户拨打电话的结果以及为客户提供的一些建议等等... ...按日期分组
但现在我想找到我尝试按lead_id
和cuncat(lead_id,timecreatredFormat)
进行分组的客户数仍然存在数据不匹配
以下是我尝试的查询
select
sum(t.enquiry_cnt),
sum(t.suggested_cnt),
sum(t.tot_cnt)
from
(select
case
when source = 1 then 1
else 0
end enquiry_cnt,
case
when source = 6 then 1
else 0
end suggested_cnt,
case
when (source = 1 || source = 6) then 1
else 0
end tot_cnt,
date_format(timecreated, '%d-%b-%Y') created_time,
lead_id,timecreated
from
mg_lead_suggested_listing group by concat(created_time,lead_id) ) t
group by t.created_time
order by t.timecreated desc
limit 10;
提前致谢
答案 0 :(得分:0)
检查以下查询是否正确。我添加了COUNT(DISTINCT t.lead_id)来获取客户数量。
DECLARE @TEMP TABLE
(
[source] INT,
lead_id INT,
timecreated DATETIME
)
INSERT INTO @TEMP VALUES (1,1,GETDATE())
INSERT INTO @TEMP VALUES (6,1,GETDATE())
INSERT INTO @TEMP VALUES (6,1,GETDATE())
INSERT INTO @TEMP VALUES (1,2,DATEADD(d,-1,GETDATE()))
INSERT INTO @TEMP VALUES (1,1,DATEADD(d,-1,GETDATE()))
INSERT INTO @TEMP VALUES (1,1,DATEADD(d,-1,GETDATE()))
SELECT
CAST(t.timecreated AS DATE) [date],
SUM(t.enquiry_cnt) enquiry_cnt,
(SELECT COUNT(DISTINCT lead_id) FROM @TEMP WHERE CAST(timecreated AS DATE) = CAST(t.timecreated AS DATE) AND [source] = 1) as lead_enquiry_cnt,
SUM(t.suggested_cnt) suggested_cnt,
(SELECT COUNT(DISTINCT lead_id) FROM @TEMP WHERE CAST(timecreated AS DATE) = CAST(t.timecreated AS DATE) AND [source] = 6) as lead_suggested_cnt,
SUM(t.tot_cnt) tot_cnt,
COUNT(t.lead_id) as lead_cnt
FROM
(
SELECT
CASE
WHEN [source] = 1 THEN 1
ELSE 0
END enquiry_cnt,
CASE
WHEN [source] = 6 THEN 1
ELSE 0
END suggested_cnt,
CASE
WHEN ([source] = 1 OR [source] = 6) THEN 1
ELSE 0
END tot_cnt,
lead_id,
timecreated
FROM
@TEMP
) AS t
group by
CAST(t.timecreated AS DATE)
order by
[date] desc