我在MSSQL中编写了以下查询:
Select customer.name,
max(callnote.ID),
CAST (callnote.NOTE as VARCHAR(100))
from callnote
join CONTACT
on
contact.ID=callnote.CONTACT_ID
join CUSTOMER
on
customer.ID=contact.CUSTOMER_ID
where callnote.TYPE='n' and CUSTOMER.AcctClass>='1'
group by customer.NAME, CAST (callnote.NOTE as VARCHAR(100))
order by customer.NAME
我希望每个客户名称只能收到一条记录(最后一条记录)。 (789行,当我离开' CAST(callnote.NOTE as VARCHAR(100))'查询时得到的)我得到的是相信我是每个联系人的最后一个音符( 11,500多行)。我已经绞尽脑汁待了好几个小时,并重写了这么多次。 customer表和callnote表之间没有公共列。如何才能显示每个CUSTOMER的最后一个音符?
答案 0 :(得分:0)
我假设您需要来自最大注释ID的注释中的注释?所以像这样:
Select
C.name,
n.ID,
n.NOTE
from
CUSTOMER c
outer apply (
select top 1
callnote.ID,
CAST (callnote.NOTE as VARCHAR(100))
from
CONTACT
join callnote
on contact.ID=callnote.CONTACT_ID and callnote.TYPE='n'
where
c.ID=contact.CUSTOMER_ID
order by
callnote.ID desc) n
where
c.AcctClass>='1'
order by
c.NAME
因此,它始终从该客户的最大ID中获取行。希望语法没问题,不能真正测试这个。
答案 1 :(得分:0)
你能试试吗
SELECT Name, MAX(CallNoteID) CallNoteID, CallNote
FROM
(
SELECT Customer.Name,
CallNote.ID CallNoteID,
TRIM(CAST(CallNote.Note as VARCHAR(100))) CallNote
FROM CallNote
JOIN Contact ON Contact.ID = CallNote.CONTACT_ID
JOIN Customer ON Customer.ID = Contact.CUSTOMER_ID
WHERE CallNote.Type = 'n' AND Customer.AcctClass >= '1'
) A
GROUP BY Name, CallNote
ORDER BY Name