将两个sql server查询合二为一

时间:2015-02-24 14:13:29

标签: sql sql-server-2008

如何在一个

中组合这两个选择
 SELECT TOP 5 Sum([NumOfChats]) AS [NumOfChats]
            ,[CaseTypeName]
            ,[CaseSubTypeName]
      FROM #Result2
      GROUP BY [CaseTypeName]
            ,[CaseSubTypeName]

      SELECT Sum([NumOfChats]) AS [TotalNumOfChats]           
      FROM #Result2

首先查询前5个NumOfChats,第二个查询NumOfChats。

所以我想以同一行为例: 5,Some_CaseTypeName,Some_CaseSubTypeName,10(这是聊天总数)

2 个答案:

答案 0 :(得分:2)

使用UNION ALL,在第二个查询中选择NULL以获得与第一个查询中相同的列数:

SELECT TOP 5 Sum([NumOfChats]) AS [NumOfChats]
            ,[CaseTypeName]
            ,[CaseSubTypeName]
      FROM #Result2
      GROUP BY [CaseTypeName]
            ,[CaseSubTypeName]
UNION ALL
      SELECT Sum([NumOfChats]) AS [TotalNumOfChats], NULL, NULL           
      FROM #Result2

答案 1 :(得分:0)

DECLARE @T int = (SELECT Sum([NumOfChats])   
      FROM #Result2 )

  SELECT TOP 5 Sum([NumOfChats]) AS [NumOfChats]
        ,[CaseTypeName]
        ,[CaseSubTypeName]
        ,@T [TotalNumOfChats]    
  FROM #Result2
  GROUP BY [CaseTypeName]
        ,[CaseSubTypeName]