Skip to content
Advertisement

SQL How to avoid groupby

I have this query that it results is not correct and I assume it groupby issue

Fiddle

This is my dbfiddle

Query

SELECT  UPPER(reg.Title) as TITLE1, 
        UPPER(cust.[Name]) as CUSTOMER,
        Rmember.DisplayName as  USERNAME, 
        Rmember.Email as USEREmail,
    COUNT(dbo.Request.Id) as REQUESTS
FROM    dbo.Customer as cust INNER JOIN
         dbo.Registry as reg ON cust.Id = reg.CustomerId INNER JOIN
         dbo.RegistryMember as Rmember ON reg.Id = Rmember.RegistryId full JOIN
         dbo.Request ON reg.Id = dbo.Request.RegistryId
WHERE   Rmember.Email like '%PNEVMA%'
group by  reg.Title, cust.[Name], Rmember.DisplayName,Rmember.Email
order by  reg.Title

Result

enter image description here

Expected

In reality only user1 has done 4 requests

enter image description here

Advertisement

Answer

Your result shows one registry with ‘Title1’. Per registry you can have many users (in table RegistryMember). And per registry you can have many requests (in table Request).

Now you say that you get wrong counts, because only ‘User 1’ made requests. There is nothing in your query, though, to link a request to a user. So obviously you are missing this in your join. (A full outer join makes no sense in your query by the way). The join should look something like this:

LEFT JOIN dbo.Request ON reg.Id = Request.RegistryId and Rmember.UserId = Request.UserId

or

LEFT JOIN dbo.Request ON Rmember.RegistryId = Request.RegistryId
                     AND Rmember.UserId = Request.UserId

because a request links to a request member.

You must adapt this to your actual table columns of course. I just saw your db fiddle and became a little confused by RequestedBy_Id linking to a member ID or a registry member ID (which I do not know, nor do I know the difference between the two) and by RequestedBy_Name and RequestedBy_Email which can obviously be different from the real/current (?) name and email of the registry member and maybe even from that of the member. All this looks a bit redundant, but this may be on purpose. You will know, what columns to actually join the tables on.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement