SQL服务器从子查询中多次计数的总和
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL服务器从子查询中多次计数的总和相关的知识,希望对你有一定的参考价值。
我试图在SQl服务器中将多个计数的单个总和作为单行。下面是我的查询不起作用的示例
SELECT
SUM(A), SUM(B), SUM(C)
FROM
(
SELECT
COUNT(CASE T.ID WHEN 1 THEN T.ID END, '', 0) AS [A]
COUNT(CASE T.ID WHEN 2 THEN T.ID END, '', 0) AS [B]
COUNT(CASE T.ID WHEN 3 THEN T.ID END, '', 0) AS [C]
FROM
MyTable AS T
INNER JOIN MyOtherTable AS MOT ON T.IDNum = MOT.IDNum
WHERE
YEAR(T.MyDate) = 2015
)
这会抛出无效的语法,因为我需要为子查询添加别名。有关如何使其工作的任何想法?
答案
您只需要为子查询添加别名。它看起来应该是这样的。
SELECT
SUM(alias_query_name.A), SUM(alias_query_name.B), SUM(alias_query_name.C)
FROM
(SELECT
COUNT(CASE T.ID WHEN 1 THEN T.ID END, '', 0) AS [A]
COUNT(CASE T.ID WHEN 2 THEN T.ID END, '', 0) AS [B]
COUNT(CASE T.ID WHEN 3 THEN T.ID END, '', 0) AS [C]
FROM
MyTable AS T
INNER JOIN MyOtherTable AS MOT ON T.IDNum = MOT.IDNum
WHERE
YEAR(T.MyDate) = 2015
) as alias_query_name -- <----- name of sub query
以上是关于SQL服务器从子查询中多次计数的总和的主要内容,如果未能解决你的问题,请参考以下文章