0

I have a table with columns UserID, SiteID, SiteViews and another with UserID, First, Last

And I need to display the data as First + Last, Site1Views, Site2Views

There are only 2 site IDs and I need to have the sum of the SiteViews per User.

Currently I have:

select s.UserFirstName + ' ' + s.UserLastName as 'Name', 
j1.SiteViews as 'Site1Name',
j2.SiteViews as 'Site2Name' 
from (Users s INNER JOIN Usage j on s.UserID = j.UserID)

I don't know how to do this. Any help would be appreciated.

2
  • What are the primary/foreign key relationships between these tables? Commented Nov 5, 2012 at 23:28
  • UserID is the relationship being used. There is UsageID on the first table as the primary key as well. Commented Nov 5, 2012 at 23:38

2 Answers 2

1

Sounds like you might want to use PIVOT for this? I can't test it, but this should get you going int he right direction?

select s.UserFirstName + ' ' + s.UserLastName as Name, 
       [Site1Name],
       [Site2Name]
FROM
       (SELECT s.UserFirstName + ' ' + s.UserLastName,
               SiteName,
               SiteVisits
        from Users s 
        INNER JOIN Usage j1 
          on s.UserID = j1.UserID
       )
PIVOT (SUM(SiteVisits) FOR SiteName IN ([Site1Name],[Site2Name])) as p
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! To be clear, the OtherUsageTable is the same as the first Usage table. i.e. I have UserID 1, SiteID 1, Views 200, UserID 1, SiteID 2, Views 300. Your statement did separate the 2 sites but the UserIDs aren't grouped and the Views are coming across in multiple records still.
I updated my answer. Not sure if it will work, but hopefully it will point you in the right direction
1

how I understood it

select s.UserFirstName + ' ' + s.UserLastName as Name 
,(Select COUNT(*) from SiteViews s1 where s.UserID = s1.UserID /*other condition*/) as SiteView1
,(Select COUNT(*) from SiteViews s2 where s.UserID = s2.UserID /*other condition*/) as SiteView2 
from Users s 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.