简体   繁体   中英

Too many results in query

I'm fetching some data from our database in MSSQL. Out of this data I want to determine who created the client entry and who took the first payment from this client.

There can be many payment entries for a client on a single booking/enquiry and at the moment, my query shows results for each payment. How can I limit the output to only show the first payment entry?

My query:

SELECT 
 c.FirstName,
 c.LastName,
 c.PostalCode,
 o.OriginOfEnquiry,
 s.SuperOriginName,
 c.DateOfCreation,
 DATEDIFF(day, c.DateOfCreation, p.DateOfCreation) AS DaysToPayment,
 pc.PackageName,
 CONCAT(u.FirstName, ' ', u.LastName) AS CreateUser,
 (SELECT CONCAT(u.FirstName, ' ', u.LastName)  
   WHERE u.UserID = p.UserID ) AS PaymentUser

FROM tblBookings b

INNER JOIN tblPayments p
 ON b.BookingID = p.BookingID
INNER JOIN tblEnquiries e
 ON e.EnquiryID = b.EnquiryID
INNER JOIN tblCustomers c
 ON c.CustomerID = e.CustomerID
INNER JOIN tblOrigins o
 ON o.OriginID = e.OriginID
INNER JOIN tblSuperOrigins s
 ON s.SuperOriginID = o.SuperOriginID
INNER JOIN tblBookingPackages bp
 ON bp.bookingID = p.BookingID
INNER JOIN tblPackages pc
 ON pc.PackageID = bp.packageID
INNER JOIN tblUsers u
 ON u.UserID = c.UserID

WHERE c.DateOfCreation >= '2016-06-01' AND c.DateOfCreation < '2016-06-30'
AND p.PaymentStatusID IN (1,2)
AND e.CustomerID = c.CustomerID
AND p.DeleteMark != 1
AND c.DeleteMark != 1
AND b.DeleteMark != 1
;

I tried adding a "TOP 1" to the nested select statement for PaymentUser, but it made no difference.

Instead of table tblPayments specify sub-query like this:

(SELECT TOP 1 BookingID, UserID, DateOfCreation
FROM tblPayments
WHERE DeleteMark != 1
AND PaymentStatusID IN (1,2)
ORDER BY DateOfCreation) as p

您可以与top 1 cross apply

FROM tblBookings b cross apply (select top 1 * from tblPayments p where b.BookingID = p.BookingID) as p

I'm assuming that tblPayments has a primary key column ID . If it is true, you can use this statment:

FROM tblBookings b

INNER JOIN tblPayments p ON p.ID = (
  SELECT TOP 1 ID
  FROM tblPayments
  WHERE BookingID = b.BookingID
    AND DeleteMark != 1
    AND PaymentStatusID IN (1,2) 
  ORDER BY DateOfCreation)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM