我正在尝试运行查询以从表中选择信息,其中基于时间和另一个条件满足其他两个条件。
表格是:
铅
lead_id lead_bname lead_tname lead_created
1 ABC Stores ABC 2015-06-01 12:20:50
2 DEF Hutt DEF 2015-07-13 13:52:06
主管所有者
lead_owner_id lead_id staff_id lead_owner_timestamp
1 1 105 2015-06-01 12:20:50
2 1 103 2015-06-01 12:20:51
3 2 105 2015-07-13 13:52:06
潜在客户状态
lead_status_id lead_id status_ID lead_status_timestamp
1 1 54 2015-06-01 12:20:50
2 1 56 2015-06-06 10:14:55
3 2 54 2015-07-13 13:52:06
使用查询我需要获取 lead_bname 和 lead_tname ,其中时间戳(未创建)具有动态时间范围。 (例如2015-06-01 - > 2015-06-03)然后匹配到当时的特定staff_id,即使它已经更改或更早。状态再次相同。
我尝试了下面的内容,但得到了0结果。
SELECT l.lead_id, lead_bname, lead_tname, lead_created
FROM lead l, lead_owner o, lead_status s
WHERE lead_owner_timestamp = (
SELECT max(lead_owner_timestamp)
FROM lead_owner
WHERE lead_ID = l.lead_ID)
AND ( lead_owner_timestamp <= '2015-06-01' AND lead_owner_timestamp >= '2015-06-03')
AND staff_id = '103'
AND lead_status_timestamp = (
SELECT max(lead_status_timestamp)
FROM lead_status WHERE lead_ID = l.lead_ID)
AND status_ID = '54'
AND ( lead_status_timestamp <= '2015-06-01' AND lead_status_timestamp >= '2015-06-03')
预期结果
lead_bname lead_tname lead_created status_id
ABC Stores ABC 2015-06-01 12:20:50 54
这是因为在这两个日期之间创建了潜在客户,状态设置为'54',staff_id被指定为'103'作为最新条目。 如果工作人员被选为“105”,我希望得到0结果,这对我来说仍然有用。
真的坚持这个,想象我会要求一些内部或外部联接,但它有点超出我,所以希望有人在这里可以提供帮助。
答案 0 :(得分:3)
你是对的,你需要加入和一些内在的选择。试试这个:
SELECT l.lead_bname, l.lead_tname, l.lead_created, ls.status_id
FROM lead l
INNER JOIN
(SELECT lead_owner_id, lead_id, staff_id, lead_owner_timestamp
FROM lead_owner
WHERE lead_owner_timestamp = (SELECT MAX(lead_owner_timestamp) FROM lead_owner WHERE staff_id = 103)
AND lead_owner_timestamp >= '2015-06-01'
AND lead_owner_timestamp <= '2015-06-03'
AND staff_id = 103
) lo ON l.lead_id = lo.lead_id
INNER JOIN
(SELECT lead_status_id, lead_id, status_id, lead_status_timestamp
FROM lead_status
WHERE lead_status_timestamp >= '2015-06-01'
AND lead_status_timestamp <= '2015-06-03'
AND status_id = 54
) ls ON l.lead_id = ls.lead_id
请注意,使用此新版本时,您需要更改WHERE staff_id = 103
和第9行{{ 1}}。我创建了一个测试数据库,其中包含您在其中提供的所有数据,并且当工作人员ID为103时返回您预期的行,而当它为105时则返回任何内容。
答案 1 :(得分:0)
当您检查日期时,只有部分必须将日期时间转换为日期,如此
SELECT l.lead_bname, l.lead_tname, l.lead_created, ls.status_id
FROM lead l
INNER JOIN lead_owner lo ON l.lead_id = lo.lead_id
INNER JOIN lead_status ls ON l.lead_id = ls.lead_id
WHERE (
CONVERT(lo.lead_owner_timestamp,DATE) <= '2015-06-01'
AND CONVERT(lo.lead_owner_timestamp,DATE) >= '2015-06-03'
)
AND (
CONVERT(ls.lead_status_timestamp,DATE) <= '2015-06-01'
AND CONVERT(ls.lead_status_timestamp,DATE) >= '2015-06-03'
)
AND ls.status_id = 54