T-SQL中选择受HAVING属性限制的原始值的方法是什么?例如,如果我有

A|B
10|1
11|2
10|3


我如何获得按A分组,且计数(A的出现次数)大于或等于2 2的B的所有值(不是平均值或其他汇总统计量)?

最佳答案

实际上,您有几种选择

1.您可以从原始的hading语句中进行子查询,然后将其联接回表中

SELECT *
FROM   YourTable yt
       INNER JOIN (
         SELECT A
         FROM   YourTable
         GROUP BY
                A
         HAVING COUNT(*) >= 2
       ) cnt ON cnt.A = yt.A


2.另一个等效的解决方案是使用WITH子句

  ;WITH cnt AS (
    SELECT A
    FROM   YourTable
    GROUP BY
           A
    HAVING COUNT(*) >= 2
  )
      SELECT *
      FROM   YourTable yt
             INNER JOIN cnt ON cnt.A = yt.A


3.或者您可以使用IN语句

      SELECT *
      FROM   YourTable yt
      WHERE  A IN (SELECT A FROM YourTable GROUP BY A HAVING COUNT(*) >= 2)

10-08 14:58