使用group by运行UNION

时间:2015-04-14 11:57:06

标签: sql sql-server

我需要帮助将UNION与group by使用。

我编写了以下代码,为您提供了我的代码概述。我基本上试图用UNION运行这个代码超过x个月。

每次运行以下代码时,SQL SERVER都会抱怨“类别”不在组中。

我尝试将其添加到代码的末尾:

按名称分组 按名称排序

当我试图同时获取所有月份数据时,它仍然无效。

如何使用UNION子句运行查询?

SELECT
   '2000' AS Year,
    Name AS Category,
    COUNT(id) AS X
FROM
(          
    (
        Select id, Name
        From dbo.tablea
        where something
        GROUP BY id,name
        HAVING SUM(X)>0
    ) sub

    Union 

    SELECT 
        '1999' AS Year,
        Name AS Category,
        COUNT(id) AS X
    FROM
    (          
        (
            Select id, Name
            From dbo.tablea
            where something
            GROUP BY id,name
            HAVING SUM(X)>0
        ) sub

1 个答案:

答案 0 :(得分:0)

让我们看一下查询的第一部分:

SELECT '2000' AS Year, Name AS Category, COUNT(id) AS X
FROM
(
  Select id, Name
  From dbo.tablea
  where ...
  GROUP BY id, Name
  HAVING SUM(X)>0
) sub

(我删除了一个不在那里的左括号。)

你在这里使用聚合(COUNT(id),顺便说一下,它与简单的COUNT(*)相同,因为ID永远不应为null。那么您选择哪些其他领域?文字' 2000'没关系,还有姓名。但是哪个名字? MAX? MIN?你没有指定它,这就是DBMS告诉你的。所以 使用名称上的聚合,例如MIN(Name) 组(通过在" sub&#34之后添加GROUP BY Name ;别名),以便每个名称获得一行。

以下是按名称分组的完整查询:

SELECT '2000' AS Year, Name AS Category, COUNT(id) AS X
FROM
(
  Select id, Name
  From dbo.tablea
  where ...
  GROUP BY id, Name
  HAVING SUM(X)>0
) sub
GROUP BY Name
UNION
SELECT '1999' AS Year, Name AS Category, COUNT(id) AS X
FROM
(
  Select id, Name
  From dbo.tablea
  where ...
  GROUP BY id, Name
  HAVING SUM(X)>0
) sub
GROUP BY Name;