2

我很抱歉,因为我是 SQL 和 stackoverflow 的新手。另外,我没有设计数据库,目前无法更改。我有以下表格:

客户(ClientId , Client_Name)
Client_Purchases (Purchase_id, ClientID, Credits, Credits_logged)
Service_Log (LogId, Purchase_id, log_date)

我想显示所有积分为 0 的客户,按最近的 log_date 排列。为此,我想先取总和(Credits - Credits_logged),如果它们等于 0,那么我知道客户没有剩余信用(记住客户可以有多个 Client_Purchases)。然后按最近的 log_date 安排,这似乎是我遇到问题的地方。

如果我执行以下操作:

SELECT  a.ClientId, a.Client_Name, (max(c.log_date))
FROM `Client_Purchases` AS a, Clients AS b, Service_Log AS c
WHERE b.ClientId=a.ClientId AND a.Purchase_id = c.Purchase_id
GROUP BY a.ClientId
HAVING sum(a.Credits-a.Credits_logged) = 0
ORDER BY (max(c.log_date)) DESC

这几乎是正确的,只是它仍然显示可能已经购买的客户。我认为问题在于通过 Purchase_id 连接表的某个地方。任何帮助将不胜感激!

4

1 回答 1

1

您是否尝试过这样做:-

 SELECT a.ClientId, a.Client_Name, (max(c.log_date)) 
 FROM Client_Purchases AS a, Clients AS b, Service_Log AS c
 WHERE b.clientid=a.clientid       //stuid is not a column in your table as mentioned
 AND a.Purchase_id = c.Purchase_id 
 GROUP BY a.ClientId 
 HAVING sum(a.Credits-a.Credits_logged) = 0 
 ORDER BY (max(c.log_date)) 
 DESC
于 2012-11-25T17:52:50.183 回答