0

I have to make a query which will show used numbers and used times on few columns of integer type.

For this purpose I make a small example table with code suitable to paste into pgAdmin's sql editor:

DROP TABLE IF EXISTS mynums;
CREATE TABLE mynums 
   (rowindex serial primary key, mydate timestamp, num1 integer, num2 integer, num3 integer);

INSERT INTO mynums (rowindex, mydate, num1, num2, num3)
VALUES (1,  '2015-03-09 07:12:45', 1, 2, 3),
       (2,  '2015-03-09 07:17:12', 4, 5, 2),
       (3,  '2015-03-09 07:22:43', 1, 2, 4),
       (4,  '2015-03-09 07:25:15', 3, 4, 5),
       (5,  '2015-03-09 07:41:46', 2, 5, 4),
       (6,  '2015-03-09 07:42:05', 1, 4, 5),
       (7,  '2015-03-09 07:45:16', 4, 1, 2),
       (9,  '2015-03-09 07:48:38', 5, 2, 3),
       (10, '2015-03-09 08:15:44', 2, 3, 4);

Please help to build a query which would give results of used numbers and used times in columns num1, num2 and num3 together ordered by used times.

Result should be:

number  times
2       7
4       7
1       4
3       4
5       5

2 Answers 2

2

You need to turn your columns into rows in order to be able to aggregate them:

select number, count(*)
from (
  select num1 as number
  from mynums
  union all 
  select num2
  from mynums
  union all 
  select num3
  from mynums
) t
group by number
order by number;

In general, having columns like num1, num2, num3 is a sign of a questionable database design. What happens if you need to add more numbers? It's better to create a one-to-many relationship and store the numbers associated with a rowindex in a separate table.

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

2 Comments

"questionable database design", my 2cents as well :-)
Thanks a lot "a name", work as expected. In this case fixed number of columns is acceptable now but for similar cases I would keep your advice in mind.
1

this would work:

select number, count(*) as times
FROM (
  select rowindex, mydate, num1 as number FROM mynums
  UNION ALL 
  select rowindex, mydate, num2 FROM mynums
  UNION ALL 
  select rowindex, mydate, num3 FROM mynums
) as src
 group by number
 order by count(*) desc, number

http://sqlfiddle.com/#!15/cb1a7/3

1 Comment

Thanks murison, your solution also work but "a name" was faster.

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.