从其他选择的结果中选择列

时间:2013-01-09 17:48:34

标签: sql sql-server

我有这个SQL查询:

select COUNT(batch_id) AS cc FROM tbl_associate_593932 WHERE induction_result>50 GROUP BY batch_id

此查询仅使用一列cc正确执行。现在我希望从此列中的值中获取最大值。我试过这样的事情:

select max (cc) from  (select COUNT(batch_id) AS cc FROM tbl_associate_593932 WHERE induction_result>50 GROUP BY batch_id);

然而在SQL Server中,它给了我错误:';'附近的语法不正确。期待AS,ID或Quoted_ID

和另一个错误无效的列名'cc'。

如何在SQL Server中执行此操作。可以在Oracle中完成吗?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

WITH CTE
AS
(
   select COUNT(batch_id) AS cc 
   FROM tbl_associate_593932 
   WHERE induction_result > 50 
   GROUP BY batch_id
) 
SELECT MAX(cc)
FROM CTE;

或者:

SELECT TOP(1)
  COUNT(barch_id) AS cc
FROM tbl_associate_593932 
WHERE induction_result > 50 
GROUP BY batch_id
ORDER BY cc DESC;

答案 1 :(得分:0)

使用: 从(选择COUNT(batch_id)AS cc FROM tbl_associate_593932 WHERE induction_result> 50 GROUP BY batch_id)中选择max(t.cc)作为t;