1

i have a table which i group by one column and then i output the different values and the count of this values.

activty | sum
-------------
Form    |  1
Login   |  4
Reg     |  3

here is an example-code: http://sqlfiddle.com/#!2/c6faf/2/0

but i want the different values tp the column names with one row of values (the count).

like this:

Form | Login | Reg
------------------
  1  |   4   |  3

i tried the PIVOT operation, but i'm not getting it working. what am i doing wrong?

here is my code: http://sqlfiddle.com/#!2/c6faf/35/0

thanks in advance!

br

1
  • i've put a fiddle in my response so you can check it out Commented Jun 7, 2013 at 8:57

3 Answers 3

2

Here you go

SELECT 
MAX(CASE activity WHEN 'Form' THEN mysum ELSE NULL END) AS Form,
MAX(CASE activity WHEN 'Login' THEN mysum ELSE NULL END) AS Login,
MAX(CASE activity WHEN 'Reg' THEN mysum ELSE NULL END) AS Reg
FROM (
SELECT activity, COUNT(activity) AS mysum FROM tbl_tracking
            WHERE id = 141 AND variant = 2
            GROUP BY activity
)sq

But in my opinion such formatting should be done in application layer, not in database layer.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for " formatting should be done in application layer, not in database layer."
1

Try this:

SELECT  
    SUM(IF(activity = 'Form',1,0)) as 'Form',
    SUM(IF(activity = 'Login',1,0)) as 'Login',
    SUM(IF(activity = 'Reg',1,0)) as 'Reg'
FROM 
    tbl_tracking
WHERE 
    id = 141 
    AND variant = 2

Sql Fiddle here

Comments

0

For this you need to use pivot table concept. here you go for same.

SELECT
  SUM((IF(activity='Form',1,0))) as Form,
  SUM((IF(activity='Login',1,0))) as Login,
  SUM((IF(activity='Reg',1,0))) as Reg
FROM 
  tbl_tracking
WHERE 
  id = 141 
  AND 
  variant = 2;

fiddle

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.