Duda777
Duda777

Reputation: 33

Using a value from one query in second query sql

SELECT AS, COUNT(*)
FROM Table1
HAVING COUNT(AS)>1
group BY AS;

This produces the result

AS      COUNT
5       2

I then want to use the AS value in another query and only output the end result. Is this possible.i was thinking something like.

SELECT * 
FROM 
TABLE 2 
Where AS =(
           SELECT AS, COUNT(*)
           FROM Table1
           HAVING COUNT(AS)>1
           group BY AS;
);

Upvotes: 1

Views: 319

Answers (2)

Mureinik
Mureinik

Reputation: 311338

You could use a subquery with the in operator:

SELECT *
FROM   table2
WHERE  AS IN (SELECT   AS
              FROM     table1
              GROUP BY AS
              HAVING   COUNT(*) > 1)

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269803

This is called a subquery. To be safe, you would use in instead of = (and as is a bad name for a column, because it is a SQL key word):

SELECT * 
FROM TABLE2 
WHERE col IN (SELECT col
              FROM Table1
              GROUP BY col
              HAVING COUNT(col) > 1
             );

Your first query is also incorrect, because the having clause goes after the group by.

Upvotes: 1

Related Questions