How to show all date from a certain Month by horizontally?

与世无争的帅哥 提交于 2019-12-11 17:51:07

问题


I have database table in postgreSQL name as "time" like:

|  Name  |  |    Date1   | |AttendHour1| |    Date2   | |AttendHour2|
---------------------------------------------------------------------
| Zakir1 |  | 2018-10-01 | |   8.00    | | 2018-10-02 | |   8.00    |
| Zakir2 |  | 2018-10-01 | |   9.00    | | 2018-10-02 | |   9.00    |
| Zakir3 |  | 2018-10-01 | |   7.00    | | 2018-10-02 | |   7.00    | 

From this table I want the result like..

|  Name  | | 2018-10-01 | | 2018-10-02 |
----------------------------------------
| Zakir1 | |   8.00     | |   8.00     |
| Zakir2 | |   9.00     | |   9.00     |
| Zakir3 | |   7.00     | |   7.00     |

What is postgreSQL Query ?


回答1:


As it stands, you don't even need a crosstab() query for this. Just:

SELECT name, AttendHour1 AS "2018-10-01", AttendHour2 AS "2018-10-02"
FROM   time;

If your desire is to assign column names dynamically from column values: that's not possible. SQL does not allow dynamic column names. You need a two-step workflow:

1. Create the query string dynamically.

To generate above query:

SELECT format('SELECT name, AttendHour1 AS %I, AttendHour2 AS %I FROM time'
             , date1, date2)
FROM   time
LIMIT  1;
2. Execute the query.

来源:https://stackoverflow.com/questions/53077581/how-to-show-all-date-from-a-certain-month-by-horizontally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!