Question

I need some help.

Lets say i have a table

ID  Mark  Transmition
1   Ford  A
2   Ford  A
3   Ford  M
4   BMW   M
5   BMW   M
6   Ford  A

And now i need to do a case when.

CASE WHEN mark = 'Ford' then 'Ford'
     WHEN mark = 'Ford' and Transmition = 'A' then ' including Fords with automatic transmitions'

And I have to do this using case when, not case when exists. Since I need to use it in an OBIEE report.

The result i need is something like this:

Mark                                  Count
Ford                                  4
inc Ford with automatic transmition   3

But the results evaluate to TRUE in bith of the cases...

Looking forward to hearing from you.

Was it helpful?

Solution

Query:

SELECT CASE WHEN mark = 'Ford' THEN 'Ford' END AS Mark,
COUNT(*)
FROM Table1 t
WHERE mark = 'Ford'
GROUP BY mark
UNION ALL
SELECT CASE WHEN mark = 'Ford' AND Transmition = 'A' 
              THEN 'including Fords with automatic transmitions' END AS Mark,
COUNT(*)
FROM Table1 t
WHERE mark = 'Ford'
AND Transmition = 'A' 
GROUP BY CASE WHEN mark = 'Ford' AND Transmition = 'A' 
              THEN 'including Fords with automatic transmitions' END

Result:

|                                        MARK | COUNT(*) |
|---------------------------------------------|----------|
|                                        Ford |        4 |
| including Fords with automatic transmitions |        3 |

OTHER TIPS

Not sure about your question, but it seems you try to avoid null rows by pointing out case when vs case when exists.

What about

SELECT
  ' including Fords with automatic transmitions' AS "DESCRIPTION",
  COUNT("ID") AS "POCET"
FROM some_table
WHERE "Mark" = 'Ford' AND "Transmition" = 'A'
GROUP BY "Mark"

UNION ALL

SELECT
  "Mark",
  COUNT("ID") AS "POCET"
FROM some_table
WHERE "Mark" = 'Ford'
GROUP BY "Mark"

You can do it without CASE like this :

SELECT Mark, count(1) FROM car GROUP By Mark
UNION
SELECT 'Including '||Mark||' with automatic transmitions' as MM, count(1) FROM car WHERE Transmition = 'A' GROUP By MM;

Result:

|                                        MARK | COUNT(*) |
|---------------------------------------------|----------|
|                                         BMW |        2 |
|                                        Ford |        4 |
| including Fords with automatic transmitions |        3 |

Simply try this

SELECT MARK,Count(1) AS Count FROM
 (
   SELECT CASE WHEN mark = 'Ford' and Transmition = 'A' then ' including Fords with automatic transmitions'
          WHEN mark = 'Ford' and Transmition <> 'A' then 'Ford'
          Else 'BMW'
          END Mark
   FROM Table1
) AS T Group By T.Mark

O/P :

MARK                                            COUNT
including Fords with automatic transmitions     3
BMW                                             2
Ford                                            1

FIDDLE DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top