简体   繁体   中英

Returning DISTINCT rows in sql query

I have two tables. One is clients, that has a clientID and entity, the other is LogOnLink which has a clientID and LogonID. The LogOnLink table can the same clientID entered into it multiple times. So i'm trying to run a query where I do a search for an Entity Joining the LogonLink table. The problem i'm having is that if an entity is in the logonLink table 20 times, i get the name returned twenty times. How do i make it so that it only shows me one instance of an entity. Keep in mind that there can be similar entity names so If i have "Company 1" and "Company 2" in the db, i need to show both companies if someone types in companies. I tried doing DISTINCT but it doesn't distinct it by clientID in the LogOnLink table. Here's what i have so far.

SELECT DISTINCT ll.logonID, entity 
FROM clients c 
INNER JOIN LogOnsLink ll ON ll.clientID = c.clientID 
WHERE c.entity LIKE '%Com%' 
ORDER BY entity

Clients Table
------------------------------------
clientID    entity
2             Company A
8             Company B
43            Company C

LogOnLinks Table
------------------------------------
LogonLinkID    clientID    LogonID
4                  2           3
5                  2           7
21                 8           20
6                  2           9
3                  8           10
45                 43          3

You'll need to perform some kind of aggregate on the data from LogOnsLink or you'll always get 20 rows...

Try this

SELECT entity, COUNT(ll.logonID) AS MaxlogonIDs
FROM clients c 
    INNER JOIN LogOnsLink ll ON ll.clientID=c.clientID 
WHERE c.entity LIKE '%Com%' 
GROUP BY entity
ORDER BY entity

or

SELECT DISTINCT entity
FROM clients c 
    INNER JOIN LogOnsLink ll ON ll.clientID=c.clientID 
WHERE c.entity LIKE '%Com%' 
ORDER BY entity

Try this

SELECT ll.logonID, DISTINCT(entity) 
FROM Clients c INNER JOIN LogOnsLink ll 
ON ll.clientID=c.clientID 
WHERE c.entity LIKE '%Com%' 
ORDER BY entity

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