选择何时聚合列具有两个或更多项

时间:2010-05-06 17:25:06

标签: sql group-by

假设我有这样的查询:

SELECT * FROM (
  SELECT 'a' AS a, '1' AS b
UNION 
  SELECT 'a' AS a, '2' AS b
UNION
  SELECT 'b' AS a, '1' AS b) AS a 
GROUP BY a.a 

在这种情况下,“a”.b是1,2的汇总,而“b”.b只是1的汇总。

如何只选择“a”?

问题更新更清晰:

让我们采用这个非常相似的查询:

SELECT *, GROUP_CONCAT(b) FROM (
  SELECT 'a' AS a, '1' AS b
UNION 
  SELECT 'a' AS a, '2' AS b
UNION
  SELECT 'a' AS a, '3' AS b
UNION
  SELECT 'b' AS a, '1' AS b
UNION
  SELECT 'b' AS a, '2' AS b
) AS a 
GROUP BY a.a

现在a.b是1,2,3而b.b是1,2:

我想在它有1,2和3的基础上选择一个。

3 个答案:

答案 0 :(得分:0)

SELECT  a
FROM    (
        SELECT 'a' AS a, '1' AS b
        UNION 
        SELECT 'a' AS a, '2' AS b
        UNION
        SELECT 'b' AS a, '1' AS b
        ) AS a
GROUP BY
        a
HAVING  COUNT(*) > 1

请注意,您使用的*语法是MySQL的扩展名,不应该像这样使用。

在这种情况下,

a.b不是聚合:它将是来自组'a'的随机记录。

答案 1 :(得分:0)

尝试:

SELECT a.a,COUNT(*) AS CountOf FROM (
  SELECT 'a' AS a, '1' AS b
UNION 
  SELECT 'a' AS a, '2' AS b
UNION
  SELECT 'b' AS a, '1' AS b) AS a 
GROUP BY a.a
HAVING  COUNT(*) > 1

输出:

a    CountOf
---- -----------
a    2

(1 row(s) affected)

编辑基于OP的评论:

  

这不会出现a.b.   1,2,3和b.b是1,2

试试这个:

SELECT TOP 1 a.a,COUNT(*) AS CountOf FROM (
  SELECT 'a' AS a, '1' AS b
UNION 
  SELECT 'a' AS a, '2' AS b
UNION 
  SELECT 'a' AS a, '3' AS b
UNION 
  SELECT 'b' AS a, '1' AS b
UNION
  SELECT 'b' AS a, '2' AS b) AS a 
GROUP BY a.a
ORDER BY 2 DESC

输出:

a    CountOf
---- -----------
a    3

(1 row(s) affected)

答案 2 :(得分:0)

以下似乎对我有用:

SELECT a,b FROM (
    SELECT a,b FROM (
      SELECT 'a' AS a, '1' AS b
    UNION 
      SELECT 'a' AS a, '2' AS b
    UNION
      SELECT 'a' AS a, '3' AS b
    UNION
      SELECT 'b' AS a, '1' AS b
    UNION
      SELECT 'b' AS a, '2' AS b
    ) AS a 
) b WHERE b.b IN ({x1},{x2}...)
GROUP BY b.a HAVING COUNT(b.b) = 2

其中x1等是我想要限制的“b”的值。

例如,在这种情况下

WHERE b.b IN (1,2,3)

将返回“a”

WHERE b.b IN (1,2)

将返回“a”和“b”

WHERE b.b IN (2,3) 

只会返回“a”

我不确定为什么会这样,但似乎。