没有分组,有子查询

时间:2013-10-25 09:45:51

标签: sql

我正在寻找namecounter = 3的行。 我尝试过使用过哪里但有两次都让我失望,或者我做错了什么?

这是我当前的SQL代码:

SELECT refnam, tstring,(SELECT COUNT('refnam') FROM refdev rc
                        WHERE rc.refnam = r.refnam
                        ) as namecounter
FROM refdev r, OUTER texte t
WHERE r.sigtnr = t.textnr
ORDER BY refnam

这是我目前输出的一个例子:

AAU01   AANGEVRAAGD                                                                                             4
AAU01   ACTIEF                                                                                                  4
AAU01   UIT                                                                                                     4
AAU01   AANGEVRAAGD EN ACTIEF                                                                                   4
AB001   UIT                                                                                                     2

3 个答案:

答案 0 :(得分:3)

SELECT r.refnam, 
       t.tstring,
       rc.cnt namecounter
FROM refdev r
INNER JOIN (SELECT refnam, 
                   COUNT(*) cnt
              FROM refdev rc
          GROUP BY refnam
           ) rc 
        ON rc.refnam = r.refnam
LEFT OUTER JOIN texte t
             ON r.sigtnr = t.textnr
WHERE rc.cnt = 3
ORDER BY r.refnam

答案 1 :(得分:1)

当子查询返回查询的列时,WHERE就是这样。我不理解ypercube评论的“外部”事情。

这应该起作用:

SELECT refnam, tstring, COUNT(*) as namecounter
FROM refdev r, texte t
WHERE r.sigtnr = t.textnr
GROUP BY refnam, tstring
HAVING COUNT(*)=3
ORDER BY refnam

答案 2 :(得分:0)

SELECT r.refnam, 
       t.tstring,
       rc.cnt namecounter,
       d.alarmzu
FROM refdev r
INNER JOIN (SELECT refnam, 
                   COUNT(*) cnt
              FROM refdev rc
          GROUP BY refnam
           ) rc 
        ON rc.refnam = r.refnam
LEFT OUTER JOIN texte t
             ON r.sigtnr = t.textnr
JOIN devtzu d ON d.zustnr = r.zustnr
LEFT OUTER JOIN refdev_DEF RD ON d.dvtypnr = RD.dvtypnr
WHERE r.refnam = RD.refnam
AND rc.cnt = 3
ORDER BY r.refnam