1

我想知道是否有人可以将目光投向我正在尝试执行的查询,我想不出最好的方法。

我需要联系人表中的电子邮件、名字和姓氏以及热线表中的 HotlineID 和 Last Action。我想过滤存储在热线表中的“标志”列,只显示值为 1 的行。我通过这个查询实现了这一点:

select Email, FirstName, Surname, HotlineID, LastAction 
from Hotline 
left join contact on contact.companyid=hotline.CompanyID 
                 and contact.ContactID=hotline.ContactID 
where
hotline.Flag = 1

现在是我做不到的一点。在 Actions 表中有 3 列 'HotlineID' 'Comment' 'Date' Actions 表中的 HotlineID 链接到 HotlineID 中的 HotlineID。可以为每条热线添加多条评论,并在日期列中记录发布日期。

在第一个查询返回的行中,我想进一步过滤掉最大日期(最后记录的评论)比当前日期晚不到 48 小时的任何行。我在 Visual Studio 中使用“addwithvalue”来填充日期变量,但出于测试目的,我使用“2014-12-04”

我想出了这个,它失败了。但我不确定为什么?

Select Email, FirstName, Surname, hotline.HotlineID, LastAction 
from Hotline
left join Contact on Contact.CompanyID=Hotline.CompanyID 
                 and Contact.ContactID=Hotline.ContactID 
inner join Actions on actions.HotlineID=hotline.HotlineID 
where hotline.flag=1 and CONVERT(VARCHAR(25), Max(Date), 126) LIKE '2014-12-03%'

我正在使用 SQL Server。

4

3 回答 3

1

MAX()是一组行的聚合函数。如果它出现在选择列表中,它的使用会将您的普通查询转换为聚合查询,这似乎不是您想要的。显然 SQL Server 在您的 where 子句中根本不会接受它。

看起来你想要这样的东西:

SELECT
  Contact.Email,
  Contact.FirstName,
  Contact.Surname,
  recent.HotlineID,
  Hotline.Action
FROM
  (SELECT HotlineID, MAX([Date]) as maxDate
    FROM Hotline
    GROUP BY HotlineID) recent
  INNER JOIN Hotline
    ON recent.HotlineId = Hotline.HotlineId
  LEFT JOIN Contact
    ON Hotline.HotlineId = Contact.HotlineId
WHERE
  datediff(hour, recent.maxDate, GetDate()) < 48
  AND Hotline.Flag = 1

可能您想将该WHERE子句放在子查询中。结果查询的含义与上面的查询略有不同,我不确定您真正想要的是哪个。

于 2014-12-04T16:22:18.010 回答
0

除了在派生表中使用您的 Hotlines 表而不是您的 Actions 表之外,John 的查询也很好。

SELECT Email, FirstName, Surname, HotlineID, LastAction 
FROM Hotline h
INNER JOIN
(SELECT hotlineID, max(date) as Date FROM actions a1 GROUP BY hotlineID) a
ON h.hotlineID = a.hotlineID
LEFT JOIN contact c 
ON c.companyid=h.CompanyID and c.ContactID=h.ContactID          
WHERE
hotline.Flag = 1 
and datediff(hour,[Date],getdate()) > 48
于 2014-12-05T16:07:41.737 回答
0

You can try this

Select Email, FirstName, Surname, hotline.HotlineID, LastAction 
from Hotline
left join Contact on Contact.CompanyID=Hotline.CompanyID 
                 and Contact.ContactID=Hotline.ContactID 
inner join Actions on actions.HotlineID=hotline.HotlineID 
where hotline.flag=1 
  and CONVERT(VARCHAR(25), Max(Date), 126) < CONVERT(VARCHAR(25), GetDate() - 2, 126) 
于 2014-12-04T16:12:35.017 回答