简体   繁体   English

PostgreSQL在多列上选择

[英]PostgreSQL Select on multiple columns

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: 为此,我制作了一个小的示例表,其中包含适合粘贴到pgAdmin的sql编辑器中的代码:

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. 请帮助构建一个查询,该查询将在num1,num2和num3列中给出使用数字和使用时间的结果,并按使用时间排序。

Result should be: 结果应为:

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

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. 通常,具有num1,num2,num3之类的列表明数据库设计存在问题。 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. 最好创建一对多关系并将与行rowindex关联的数字存储在单独的表中。

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 http://sqlfiddle.com/#!15/cb1a7/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM