0

我有一个带有列的表UserID, SiteID, SiteViews和另一个带有UserID, First, Last

我需要将数据显示为First + Last, Site1Views, Site2Views

只有 2 个站点 ID,我需要每个用户的 SiteViews 的总和。

目前我有:

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)

我不知道该怎么做。任何帮助,将不胜感激。

4

2 回答 2

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
于 2012-11-05T23:23:03.263 回答
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 
于 2012-11-05T23:27:35.837 回答