Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我需要在postgresql数据库中按日期分组数据,并在日期中使用_Sql_Postgresql - Fatal编程技术网

我需要在postgresql数据库中按日期分组数据,并在日期中使用

我需要在postgresql数据库中按日期分组数据,并在日期中使用,sql,postgresql,Sql,Postgresql,我需要在postgresql数据库中按日期分组数据,并在日期中使用 下面是我数据库中的示例数据 | id | user_name | date | action | ---------------------------------------- | 1 | user_1 | 2018-05-05 | start | | 2 | user_1 | 2018-05-05 | stop | | 3 | user_2 | 2018-05-05 | start

我需要在postgresql数据库中按日期分组数据,并在日期中使用

下面是我数据库中的示例数据

| id | user_name |    date    | action |
----------------------------------------
| 1  |  user_1   | 2018-05-05 | start  |
| 2  |  user_1   | 2018-05-05 | stop   |
| 3  |  user_2   | 2018-05-05 | start  |
| 4  |  user_2   | 2018-05-05 | stop   |
| 5  |  user_1   | 2018-05-06 | start  |
| 6  |  user_1   | 2018-05-06 | start  |
| 7  |  user_1   | 2018-05-06 | stop   |
| 8  |  user_2   | 2018-05-06 | start  |
| 9  |  user_2   | 2018-05-06 | stop   |
如何创建sql,以获得下表中的示例结果:

| user_name | 2018-05-05 | 2018-05-06 |
---------------------------------------
|   user_1  |     2      |     3      |
|   user_2  |     2      |     2      |

2018-05-05和2018-05-06列显示了有关该日期使用量的信息。

这是您真正想要的吗

select user_name, 
       sum( (date = '2018-05-05')::int) as date_20180505,
       sum( (date = '2018-05-06')::int) as date_20180506
from t
group by user_name;

谷歌“SQL数据透视表”…在postgresql中,数据透视是通过“是”实现的,但该表包含大量数据和许多来自多年的日期。@GrzegorzKawalec。只能回答你实际提出的问题。如果日期已存在多年,则可能无法生成所需的输出,因为Postgres允许的列数已达到最大值。如果您有关于动态枢轴的问题,我建议您问另一个问题。