HAVING子句中的2x COUNT

时间:2012-04-10 16:10:09

标签: oracle count

我有以下问题: 我想计算一个表中的数据,计算第二个表中的数据并比较having子句中的计数,并仅显示具有相同计数的行 这样的事情:

SELECT bla
FROM T1 t1 JOIN T2 t2
ON t1.id = t2.id
HAVING COUNT(counted data from table1) = COUNT(counted data from table2)
你知道吗? 干杯

2 个答案:

答案 0 :(得分:1)

标准SQL:

SELECT t1.bla, t1.id, t1.counter, t2.counter
  FROM (SELECT t1.bla, t1.id, COUNT(counted_data_from_t1) AS counter
          FROM t1
         GROUP BY t1.bla, t1.id
       ) AS t1
  JOIN (SELECT t2.id, COUNT(counted_data_from_t2) AS counter
          FROM t2
         GROUP BY t2.id
       ) AS t2
    ON t1.id = t2.id AND t1.counter = t2.counter

Oracle SQL(因为Oracle在表别名之前不喜欢AS):

SELECT t1.bla, t1.id, t1.counter, t2.counter
  FROM (SELECT t1.bla, t1.id, COUNT(counted_data_from_t1) AS counter
          FROM t1
         GROUP BY t1.bla, t1.id
       ) t1
  JOIN (SELECT t2.id, COUNT(counted_data_from_t2) AS counter
          FROM t2
         GROUP BY t2.id
       ) t2
    ON t1.id = t2.id AND t1.counter = t2.counter

你只需要决定bla的来源;我提名t1。我假设对于t1.id的任何给定值,只有t1.bla的单个值。如果没有,那么你需要更清楚地解释你在计算什么以及各列的位置,以及表的关键是什么。

更新:抱歉没有注意到Oracle标记并提供无效的Oracle语法。

答案 1 :(得分:0)

WITH jezyki as 
          (SELECT pseudo_wampira, COUNT(*) AS counter
            FROM Jezyki_obce_w
            GROUP BY pseudo_wampira
          )
    ,sprawnosc as 
         (SELECT pseudo_wampira, sprawnosc, COUNT(*) AS counter
          FROM Sprawnosci_w
         GROUP BY pseudo_wampira, sprawnosc 
         )
      SELECT jezyki.pseudo_wampira, sprawnosc.counter
        FROM jezyki,sprawnosc
       WHERE  jezyki.pseudo_wampira = sprawnosc.pseudo_wampira 
         AND  jezyki.counter = sprawnosc.counter