ryanschefke Posted September 30, 2008 Share Posted September 30, 2008 Hello, How can I construct this query? I have a bunch of values in a table. I want to output the % of values that only occur once to the % of values that occur more than once. In other words, if I have 1, 2, 2, 2, 3, 4, 4, I would like to output: New numbers: 50% Existing numbers: 50% ..new numbers because the 1 and 3 only occurred once and existing numbers of 2 and 4 because they occurred more than once. %s are %s of individual numbers. What is the query I should use? Ryan Quote Link to comment https://forums.phpfreaks.com/topic/126501-calculating-new-vs-old/ Share on other sites More sharing options...
F1Fan Posted September 30, 2008 Share Posted September 30, 2008 This should get you started. I couldn't figure out the percentage part, but you can do that after you get the results: SELECT COUNT(DISTINCT(field)) AS old, (COUNT(field)-COUNT(DISTINCT(field))) AS new, COUNT(field) AS total FROM table Quote Link to comment https://forums.phpfreaks.com/topic/126501-calculating-new-vs-old/#findComment-654237 Share on other sites More sharing options...
Barand Posted September 30, 2008 Share Posted September 30, 2008 try SELECT A.newold, COUNT(*)*100/B.totnums as pcent FROM (SELECT val, CASE COUNT(*) WHEN 1 THEN 'new' ELSE 'old' END as newold FROM mytable GROUP BY val) as A JOIN (SELECT COUNT(DISTINCT val) as totnums FROM mytable) as B GROUP BY A.newold with my data [pre] +------+ | val | +------+ | 2 | | 3 | | 5 | | 4 | | 2 | | 5 | +------+ --> 'new', 50.0000 'old', 50.0000 Quote Link to comment https://forums.phpfreaks.com/topic/126501-calculating-new-vs-old/#findComment-654239 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.