Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm not getting the desired output

What I have tried:

the code i have used is

SELECT u.name
FROM user as u, query as q
WHERE u.id = q.user_id
GROUP BY u.name HAVING COUNT(q.user_id) = 2
ORDER BY u.name;
Posted
Updated 26-Oct-17 1:34am

Your going to have to give a lot more information about what your desired output is. You are probably not seeing what you want as you've got a HAVING clause in your query. Otherwise your query looks like it is probably correct.

See example schema/data below

SQL
DECLARE @Users TABLE  (
	Id INT NULL,
	Username VARCHAR(200) NULL
);

DECLARE @Query TABLE (
	UserId INT NULL,
	Query VARCHAR(200) NULL
);

INSERT INTO @Users (Id,Username) VALUES (1,'user1')
INSERT INTO @Users (Id,Username) VALUES (2,'user2')

INSERT INTO @Query (UserId, Query) VALUES (1, 'A');
INSERT INTO @Query (UserId, Query) VALUES (2, 'A');
INSERT INTO @Query (UserId, Query) VALUES (2, 'A');
INSERT INTO @Query (UserId, Query) VALUES (2, 'A');
INSERT INTO @Query (UserId, Query) VALUES (2, 'A');


SELECT 
	A.Username,
	COUNT(*)
FROM @Users AS A
JOIN @Query AS B ON B.UserId = A.Id
GROUP BY A.Username
ORDER BY A.Username


Then the output of this is

Username	ItemsAnswered
user1	            1
user2	            4



Which is ordered by the username
 
Share this answer
 
SELECT u.name FROM user as u, query as q
WHERE u.id=q.user_id and q.parent_id is NOT NULL
GROUP BY u.name HAVING COUNT(q.user_id) = 2
ORDER BY u.name;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900