Skip to content
Advertisement

SQL COUNT with condition and without – using JOIN

My goal is something like following table:

Key      | Count since date X | Count total
1        | 4                  | 28

With two simple selects I could gain this values: (the key of the table consists of 3 columns [t$ncmp, t$trav, t$seqn])

1. SELECT COUNT(*) FROM  db.table WHERE t$date >= sysdate-2 GROUP BY t$ncmp, t$trav, t$seqn
2. SELECT COUNT(*) FROM  db.table GROUP BY t$ncmp, t$trav, t$seqn

How can I join these statements?

What I tried:

SELECT n.t$trav, COUNT(n.t$trav), m.total FROM db.table n 
LEFT JOIN (SELECT t$ncmp, t$trav, t$seqn, COUNT(*) as total FROM db.table
           GROUP BY t$ncmp, t$trav, t$seqn) m 
ON (n.t$ncmp = m.t$ncmp AND n.t$trav = m.t$trav AND n.t$seqn = m.t$seqn)
WHERE n.t$date >= sysdate-2
GROUP BY n.t$ncmp, n.t$trav, n.t$seqn

I tried different variantes, but always got errors like ‘group by is missing’ or ‘unknown qualifier’. Now this at least executes, but total is always 2.

T$TRAV  COUNT(N.T$TRAV) TOTAL
4       2                   2
29      3                   2
51      1                   2
62      2                   2
16      1                   2
....

If it matter, I will run this as an OPENQUERY from MSSQLSERVER to Oracle-DB.

Advertisement

Answer

I’d try

GROUP BY n.t$trav, m.total

You typically GROUP BY the same columns as you SELECT – except those who are arguments to set functions.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement