我有一个显示客户交易的表。我的目标是列出最新交易的客户(MAX trans_Date)
表格如下所示
**tblTransaction**
transId custServId transDate
10 3 2013-12-24 11:10:57.390
11 4 2013-12-25 11:10:57.390
12 5 2013-12-26 11:10:57.390
13 6 2013-12-27 11:10:57.390
**tblCustomerService**
custServId custId custServices
3 2 Bill Payment
4 2 Recharge
5 3 Renewal
6 4 BillPayment
**tblCustomer**
custId custName custAddress
2 Arun test1
3 Rahul test2
4 Kumar test3
期望的结果应该是
custId custName LastTransactionDate
2 Arun 2013-12-25 11:10:57.390
3 Rahul 2013-12-26 11:10:57.390
4 Kumar 2013-12-27 11:10:57.390
我已经尝试了以下查询,但我没有得到所需的结果。这些值都在显示
Select c.Cust_CustID as custId,
c.Cust_CustName as custName,
c.Cust_Mobno as custMob,
c.Cust_EmailID as custEmail,
Max(e.Enq_EnqDate) as transactionDate
from dbo.EP_Enquiry e
inner join dbo.EP_CustomerServices cs on cs.CustServ_CustServID=e.CustServ_CustServID
inner join dbo.EP_Customer c on c.Cust_CustID=cs.CustServ_CustID
group by c.Cust_CustID,c.Cust_CustName,c.Cust_Mobno,c.Cust_EmailID,e.Enq_EnqID
order by transactionDate desc
答案 0 :(得分:2)
尝试此查询:
SELECT
tblCustomer.*,
T.MaxDate
FROM tblCustomer
LEFT JOIN
( SELECT tblCustomerService.custId,
MAX(tblTransaction.transDate) as MaxDate
FROM tblTransaction
JOIN tblCustomerService on
tblCustomerService.custServId=tblTransaction.custServId
GROUP BY tblCustomerService.custId
) as T
on tblCustomer.custId = T.custId
答案 1 :(得分:0)
您可以这样使用:
SELECT TC.custID,TC.custName, TTRANS.transDate FROM
tblTransaction TTRANS
INNER JOIN
tblCustomerService TCS ON TTRANS.custServId = TCS.custServId
INNER JOIN tblCustomer TC ON TCS.custId = TC.custId
WHERE TTRANS.transDate = (SELECT MAX(transDate) FROM tblTransaction b WHERE TCS.custId = b.custId)