我有一个包含UserID, SiteID, SiteViews
列的表和另一个包含UserID, First, Last
我需要将数据显示为First + Last, Site1Views, Site2Views
只有2个站点ID,我需要拥有每个用户SiteView的总和。
目前我有:
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)
我不知道该怎么做。任何帮助将不胜感激。
答案 0 :(得分:1)
听起来你可能想要使用PIVOT吗?我无法测试它,但这应该让你朝着正确的方向前进?
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
答案 1 :(得分:1)
我是如何理解的
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