如何将一个查询的(元素数组)输出发送到另一个查询

时间:2016-04-25 12:16:39

标签: sql-server

SELECT SUM(Marks) AS tot
FROM [Tbl_Results]
WHERE [month] = 'Mar'
    AND [year] = '2016'
GROUP BY sname

以上查询的输出我想传递给另一个查询,说明最大的“标记”

select MAX(?)  from [Tbl_Results]  
? how to pass an argument to get an max of marks from the table

3 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点 您可以在第一个查询中创建cte,如下所示:

;WITH cte AS
(
    SELECT SUM(Marks) AS tot
    FROM [Tbl_Results]
    WHERE [month] = 'Mar'
    AND [year] = '2016'
    GROUP BY sname
)

SELECT MAX(tot)  
FROM cte  

或者你可以从中创建一个视图:

CREATE VIEW vwTot 
AS

    SELECT SUM(Marks) AS tot
    FROM [Tbl_Results]
    WHERE [month] = 'Mar'
    AND [year] = '2016'
    GROUP BY sname
GO

SELECT MAX(tot)  
FROM vwTot  

您还可以将结果插入临时表:

SELECT SUM(Marks) AS tot INTO #Temp
FROM [Tbl_Results]
WHERE [month] = 'Mar'
AND [year] = '2016'
GROUP BY sname

SELECT MAX(tot)  
FROM #Temp  

或者将其用作派生表:

SELECT MAX(tot)  
FROM (
    SELECT SUM(Marks) AS tot
    FROM [Tbl_Results]
    WHERE [month] = 'Mar'
    AND [year] = '2016'
    GROUP BY sname
) dt

答案 1 :(得分:0)

您可以将较旧的样式和select第一组结果放入临时表中。如果您需要对该中间结果集执行其他操作,这将非常有用。例如:

SELECT SUM(Marks) AS tot
INTO #results
FROM [Tbl_Results]
WHERE [month] = 'Mar'
    AND [year] = '2016'
GROUP BY sname

SELECT MAX(tot)
FROM #results

DROP TABLE #results

或者,您可以使用更新的样式并使用Common Table Expression在单个查询中获得结果:

;WITH cte AS (
    SELECT SUM(Marks) AS tot
    FROM [Tbl_Results]
    WHERE [month] = 'Mar'
        AND [year] = '2016'
    GROUP BY sname)
SELECT MAX(tot)
FROM cte;

答案 2 :(得分:0)

您可以使用子查询。因为你正在使用groupby子句,所以你还需要在你的select语句中添加sname。

select MAX(tot)  from 
(
    SELECT  sname, SUM(Marks) AS tot
    FROM [Tbl_Results]
    WHERE [month] = 'Mar'
    AND [year] = '2016'
    GROUP BY sname
) b