1

How can I improve my existing query to display the correct lookup value if the second lookup.id was used already. Would this be better if I use derived tables? sub-queries? Can someone teach me please?

PROBLEM:

RECORDS TYPE    TYPE_DESC   PROCESS_ID  STATUS  QUEUE_DESC
1       1       Queued      55          4       Queued
1       2       Cancelled   84          7       Cancelled

MY GOAL:

RECORDS TYPE    TYPE_DESC   PROCESS_ID  STATUS  QUEUE_DESC
1       1       Initial     55          4       Queued
1       2       Follow Up   84          7       Cancelled

Existing query:

SELECT 
    COUNT(q.id) as records,
    q.type,
    l.description AS type_desc,
    q.process_id,
    q.status,
    l.description AS queue_desc
FROM
    queues q,
    lookups l
WHERE
    l.id = q.status
GROUP BY q.status;

To better understand my problem, please see sqlfiddle entry: http://sqlfiddle.com/#!2/6b7d10/6

Thanks

3 Answers 3

1

You have to join "lookups" table twice.

SELECT COUNT(q.id)    AS records
      ,q.type
      ,l1.description AS type_desc
      ,q.process_id
      ,q.status
      ,l2.description AS queue_desc
FROM queues  q
    ,lookups l1
    ,lookups l2
WHERE l1.id = q.type
  and l2.id = q.status
GROUP BY q.status;

that's all.

1
  • Hey, that worked. Thanks! Will check if there is a better way like derived tables and sub-queries. Aug 20, 2014 at 3:18
1

Try this:

select count(q.id) as records, 
q.type, a.description, q.process_id, q.status, 
b.description as qdesc
from 
queues q
inner join lookups a on q.type = a.id
inner join lookups b on q.status = b.id
group by q.status

You need to join with lookups twice - once to get the type and again to get the status. Note the use of explicit join syntax with ON clause.

1

I think this is the query you want:

SELECT COUNT(q.id) as records,
       q.type,
       lt.description AS type_desc,
       q.process_id,
       q.status,
       ls.description AS queue_desc
FROM queues q join
     lookups ls
     on ls.id = q.status and ls.key = 'status' join
     lookups lt
     on lt.id = q.type and lt.key = 'type'
GROUP BY q.status;

Note that this ensures that the key type matches the values for the joins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.