如何将额外列添加到组

时间:2015-06-15 17:16:59

标签: sql sql-server tsql

我正在使用TSQL。

SELECT  
     s.Login_Name,
     COUNT( DISTINCT (isnull(s.s1CIDNumber,'')+isnull(s.s1AVATARNumber,''))) AS 'Number of Surveys For the Week Ending on 60/09/2015'    
  FROM [dbSuppHousing].[dbo].[tblSurvey]s
  inner join tblUsers u  on 
   s.Login_Name=u.UserName
  where s.Survey_DT >='06/01/2015' AND s.Survey_DT <='2015-06-09 23:59:59'       
  group by s.Login_Name

目前它显示的数据如下:

LoginName   Number of Surveys
    MrA   8
    Mrb   4
    mrc   4
    mrd   6

如何将user_id显示为另一列? User_id位于tblUser中 并且tblsurvey和tblUser在Login_Name

上都有1-1关系

所以结果应该是这样的:

 LoginName   Number of Surveys   User_ID
    MrA           8              33
    Mrb           4              55  
    mrc           4              11 
    mrd           6              07

我尝试加入这两个表并添加User_id,但每次我被众所周知的错误“User_id应该成为分组的一部分”停止时

不,我不希望User_id成为group by的一部分,我只是想将它添加到第3列。

2 个答案:

答案 0 :(得分:1)

如果user_ID是唯一的,则可以将其添加到GROUP BY而不会使记录集膨胀。您还可以将初始查询插入临时表并更新(带有更多开销)以获取user_id,如下所示:

IF OBJECT_ID('tempdb..#Users', 'U') IS NOT NULL
    DROP TABLE #Users;


CREATE TABLE #Users
            (login_Name  NVARCHAR(256),
             NumSurveys INT,
             User_ID INT)


INSERT INTO #Users(login_Name, NumSurveys)
SELECT  
     s.Login_Name,
     COUNT( DISTINCT (isnull(s.s1CIDNumber,'')+isnull(s.s1AVATARNumber,''))) AS 'Number of Surveys For the Week Ending on 60/09/2015'    
  FROM [dbSuppHousing].[dbo].[tblSurvey]s
  inner join tblUsers u  on 
   s.Login_Name=u.UserName
  where s.Survey_DT >='06/01/2015' AND s.Survey_DT <='2015-06-09 23:59:59'       
  group by s.Login_Name



UPDATE  #Users
SET  User_ID = User_ID
FROM #Users u 
INNER JOIN tblUsers u2
ON u.login_Name = u2.login_Name

答案 1 :(得分:0)

将GroupBY查询放入子选择中,并给出“a”标签。然后将整个subselect连接到tblUser并给它一个标签“b”。然后在LoginID上加入“a”和“b”。然后选择a.user_id,其余部分来自“b”

SELECT a.user_id,b.*
FROM 
(SELECT  
 s.Login_Name,
 COUNT( DISTINCT (isnull(s.s1CIDNumber,'')+isnull(s.s1AVATARNumber,''))) AS 'Number of Surveys For the Week Ending on 60/09/2015'    
  FROM [dbSuppHousing].[dbo].[tblSurvey]s
  inner join tblUsers u  on 
   s.Login_Name=u.UserName
  where s.Survey_DT >='06/01/2015' AND s.Survey_DT <='2015-06-09 23:59:59'       
  group by s.Login_Name) a inner join tblUsers b on a.Login_Name = b.Login_Name