Quantcast
Channel: dBforums – Everything on Databases, Design, Developers and Administrators
Viewing all articles
Browse latest Browse all 13329

SQL Query - So close yet so far

$
0
0
I have a complicated problem which I shall describe with some simple sample tables and my query

Tables:
Notes
NoteID Heading CreationDate UserID CustomerID2
{6 notes made by users for customers)

Customer (I am working with a database that combined two different customer tables together.)
CustomerID CustomerID2 Name CreationDate
{5 distinct customers}

User
UserID Name CreationDate
{5 distinct users}

Appt
ApptID Event EventDate CreationDate UserID CustomerID
{10 Events created by users for customers}


Query:
SELECT
(SELECT TOP 1(Note.UserID) FROM Note
WHERE
(Customer.CustomerID2 = Note.CustomerID2)
AND (Note.CreationDate <= Appt.CreationDate)
ORDER BY Note.CreationDate DESC) AS NoteUserID
FROM Appt
JOIN Customer ON Appt.CustomerID = Customer.CustomerID
WHERE
Appt.EventDate = '2013-01-14'



This would result with:
User1
User1
User2
User3
User1
NULL

I want instead:
User1 3
User2 1
User3 1
NULL 1


How might I do this without creating an additional table and querying the created table?

I would be grateful for any help provided.

Viewing all articles
Browse latest Browse all 13329

Trending Articles