Skip to content
Advertisement

output need to achieve by one query

I have table which consist data like below.

Tran_id      status
abc            d
xyz            f
mnp            d
klm            s 
anz            f

I need output in pivot :

Total No Of d: 2
Total No Of f: 2
Total No. Of s: 1
Total no Of Status : 5

I can achieve by separate queries easily but is it possible to get it done by one query?

Advertisement

Answer

You can use conditional aggregation such as

SELECT SUM(CASE WHEN status='d' THEN 1 ELSE 0 END) AS "Total # Of D",
       SUM(CASE WHEN status='f' THEN 1 ELSE 0 END) AS "Total # Of F",
       SUM(CASE WHEN status='s' THEN 1 ELSE 0 END) AS "Total # Of S",
       COUNT(*) AS "Total # Of Status"
  FROM tab

in order to return results pivoted.

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