Skip to content
Advertisement

SQL question, using an aggregate function inside a made table from a query [closed]

I feel like I’m not understanding how to do the syntax for this.

SELECT 
    main_category,
    COUNT(main_category) AS 'Kickstarters',
    CAST(SUM(if(state = 'successful', 1, 0)) AS SIGNED) AS 'Successful_Kickstarters'
FROM 
    projects
GROUP BY
    main_category; 

Results:

Music           127    63
Film & Video    170    68
Theater          20    13
Art              86    41
Design           66    29
Publishing       79    24
Photography      29    12
Technology       63    24
Dance             9     6
Fashion          52    18
Food             60    22
Games            85    40
Journalism        9     4
Crafts           17     4
Comics           33    17

My problem is that I want to figure out the biggest number within these columns, but I don’t know how to refer to them from within the query.

Advertisement

Answer

Maybe this?

SELECT main_category
      ,MAX(Kickstarters)
      ,MAX(Sucessful_Kickstarters)
      ,MAX(if(Kickstarters > Sucessful_Kickstarters, Kickstarters, Sucessful_Kickstarters))
FROM
(
    SELECT main_category
          ,COUNT(main_category) AS 'Kickstarters'
          ,CAST(SUM(if(state = 'successful', 1, 0 ) )AS SIGNED) AS 'Sucessful_Kickstarters'        
    FROM projects
    GROUP BY main_category
) DS
GROUP BY main_category
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement