如何在一个查询中显示两个结果?

时间:2016-06-14 09:20:20

标签: sql sql-server

我在下面有一个查询,可以根据它选择的11个玩家来计算每个团队的总权重:

SELECT TeamID, SUM(PlayerWeighting) as TeamWeight
    FROM (
        SELECT * FROM(
            SELECT pl.*,
                   ROW_NUMBER() OVER(PARTITION BY pl.TeamID, pl.Position ORDER BY NEWID()) AS Rnk
            FROM(
                SELECT DISTINCT p.PlayerID, p.Position, p.PlayerWeighting, p.FirstName, p.Surname, t.TeamID, t.TeamAbbreviation, f.WeekNumber
                FROM dbo.Fixture f
                INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID
                INNER JOIN dbo.Team t ON l.LeagueID = t.LeagueID
                INNER JOIN dbo.Player p ON t.TeamID = p.TeamID
                WHERE f.WeekNumber = 1) 
                pl) po
        WHERE (po.position = 'GK' and po.rnk = 1) OR 
              (po.position = 'DF' and po.rnk <= 4) OR
              (po.position = 'MF' and po.rnk <= 4) OR
              (po.position = 'FW' and po.rnk <= 2) ) as T
    GROUP BY T.TeamID

上述查询中的第二个SELECT语句实际上输出了每个团队的玩家列表(这是在我放入第一个SELECT语句之前测试总计)。

我想做的是以某种方式显示两个结果。一个结果显示团队加权,另一个结果显示参与每个团队加权的参与者。如何让上述查询在一次执行中显示两个结果?

谢谢

更新:

如果我执行整个代码,下面是查询的样子:

enter image description here

当我在查询中注释掉第一个SELECT语句时,下面是播放器加权结果:

enter image description here

我只是希望两个表在执行时单独出现。显然我不能复制查询并将其粘贴到下面并删除第一个选择语句,因为第二个查询中的玩家可能与第一个查询中生成的团队权重不同(如果有意义的话)

2 个答案:

答案 0 :(得分:2)

您应该在没有外部查询的情况下使用SUM() OVER()

    SELECT po.*,
           SUM(po.playerWeighting) OVER(PARTITION BY po.teamID) as teamWeight
    FROM(
        SELECT pl.*,
               ROW_NUMBER() OVER(PARTITION BY pl.TeamID, pl.Position ORDER BY NEWID()) AS Rnk
        FROM(
            SELECT DISTINCT p.PlayerID, p.Position, p.PlayerWeighting, p.FirstName, p.Surname, t.TeamID, t.TeamAbbreviation, f.WeekNumber
            FROM dbo.Fixture f
            INNER JOIN dbo.League l ON f.LeagueID = l.LeagueID
            INNER JOIN dbo.Team t ON l.LeagueID = t.LeagueID
            INNER JOIN dbo.Player p ON t.TeamID = p.TeamID
            WHERE f.WeekNumber = 1) 
            pl) po
    WHERE (po.position = 'GK' and po.rnk = 1) OR 
          (po.position = 'DF' and po.rnk <= 4) OR
          (po.position = 'MF' and po.rnk <= 4) OR
          (po.position = 'FW' and po.rnk <= 2)

SUM() OVER()是一种主要用于累积和的分析函数。如果在ORDER BY之后没有提到PARTITION BY,则只会返回PARTITION BY部分中提到的每个组的总和。

答案 1 :(得分:0)

虽然@ sagi的答案很好,但您有1个结果集,其中包含您需要的所有内容。但是如果你坚持2个结果,你仍然可以使用表变量,例如像

DECLARE @testTable table(column1 int, column2 varchar(100));

INSERT INTO @testTable(column1, column2)
    SELECT  1, 'abc';           -- <- you can put your query here


-- first result set
SELECT  *
FROM    @testTable;         

-- second result set
SELECT  COUNT(1) AS TotalRows
FROM    @testTable;