SQL查询合并为一行

时间:2016-01-22 14:18:26

标签: sql-server tsql

我在组合以下查询时遇到一些困难,因此结果显示在一行而不是多行:

SELECT value FROM dbo.parameter WHERE name='xxxxx.name'
SELECT dbo.contest.name AS Event_Name
FROM contest
INNER JOIN open_box on open_box.contest_id = contest.id
GROUP BY dbo.contest.name

SELECT COUNT(*) FROM open_option AS total_people

SELECT SUM(scanned) AS TotalScanned,SUM(number) AS Totalnumber
FROM dbo.open_box
GROUP BY contest_id

SELECT COUNT(*) FROM open AS reff
WHERE refer = 'True'

我想显示每列中字段的数据,类似于下图所示。任何帮助表示赞赏!

enter image description here

2 个答案:

答案 0 :(得分:2)

只有CROSS JOIN五个查询作为派生表:

SELECT * FROM (
  Query1
) AS q1
CROSS JOIN (
  Query2
) AS q2
CROSS JOIN (...

假设您的每个查询只返回一行,那么此CROSS JOIN只会产生一行。

答案 1 :(得分:2)

Tab的解决方案很好,我只想展示另一种方法。以下语句使用subqueries来获取一行中的信息:

    $scope.contactList = [];

    $scope.addToContactList = function() {
        $scope.contactList.push($scope.contact);     
        $scope.contact = {};        
    }

    $scope.removeContact = function(idx) {
        $scope.contactList.splice(idx,1); // contactList is now defined as well
    }

这需要单独查询SELECT [xxxx.name]=(SELECT value FROM dbo.parameter WHERE name='xxxxx.name'), [Event Name]=(SELECT dbo.contest.name FROM contest INNER JOIN open_box on open_box.contest_id = contest.id GROUP BY dbo.contest.name), [Total People]=(SELECT COUNT(*) FROM open_option), [Total Scanned]=(SELECT SUM(scanned) FROM dbo.open_box GROUP BY contest_id), [Total Number]=(SELECT SUM(number) FROM dbo.open_box GROUP BY contest_id), Ref=(SELECT COUNT(*) FROM open WHERE refer = 'True'); Total Scanned

更新:如果您希望Total Number进入另一个表格,那么基本上有两种方法可以做到这一点。

  1. 直接从INSERT声明创建表格:
  2. SELECT
    1. SELECT -- the fields from the first query INTO [database_name].[schema_name].[new_table_name]; -- creates table new_table_name
    2. 插入已存在的表格
      INSERT