基于日期的动态列名

时间:2019-02-28 06:51:01

标签: sql oracle

我需要使用以下模板来完成表格。例如,我需要从两个表中获取诸如Last NameFirst Name之类的数据,然后将数据存储在每个人的单独记录中。我该怎么办?

查询产生的表

+-----------------------------------------+
| Last name | First name | 1  | 2 |..| 31 |
+-----------------------------------------+
|  Andrew   |   test     |  8 | 0 |..| 8  |
+-----------------------------------------+
|  John     |   him      |  0 | 0 |..| 0  |
+-----------------------------------------+

表格用户

+-------------------------------+
| id |  first_name  | last_name |
+-------------------------------+
| 1  |     test     |   Andrew  |
+-------------------------------+
| 2  |      him     |    John   |
+-------------------------------+

表格工作

+-------------------------------------------------------+
| id  |  person_id  |  date_created |  number_of_hours  |
+-------------------------------------------------------+
| 1   |      1      |   01.01.2019  |        8          |
+-------------------------------------------------------+
| 2   |      1      |   02.01.2019  |        0          |
+-------------------------------------------------------+
...
+-------------------------------------------------------+
| 31  |      1      |   31.01.2019  |        8          |
+-------------------------------------------------------+
| 32  |      2      |   01.01.2019  |        0          |
+-------------------------------------------------------+
...

我也尝试过获得像星期一,..,星期日这样的日期名称,我有这个

select n, case TO_CHAR( to_date(n||'.01','dd.mm'),'D')
          when '1' then n||' D'
          when '2' then 'L'
          when '3' then 'Ma'
          when '4' then 'Mi'
          when '5' then 'J'
          when '6' then 'V'
          when '7' then 'S' else 'no data'
       end d from
   (select rownum n from dual connect by level <= 31)
where n >= 1

我知道我不能这样使用,但是如何执行此查询呢?谢谢

SELECT
    a.last_name
   ,a.first_name
   ,  -- {this is what i can't figure out how to do it}
FROM users a
INNER JOIN work b
on a.id = b.person_id

2 个答案:

答案 0 :(得分:4)

据我所知,您想按天和用户将表工作的小时数分组。这可以通过使用数据透视子句来实现:

 class MyClass<T>
{
    T field;
    public void myMethod()
    {
       field = (T)new Object(); // works
    }
}

如果您只想按天分组,则可以按以下方式实现:

    select * FROM (
    SELECT
        a.last_name
       ,a.first_name
       ,w.date_created
       ,w.number_of_hours
    FROM users a
        JOIN work w on a.id = w.person_id
    ) PIVOT (
      sum(number_of_hours)
      FOR date_created
      IN (date '2019-01-01' as "2019-01-01", DATE '2019-01-01' as "2019-01-02")
      )

答案 1 :(得分:3)

如果您要存储姓氏,名字和1到31天之间的数据,请尝试使用“数据透视”子句(在Oracle中有效)。应该有帮助

select * from (-- subquery
  select a.last_name ,a.first_name
  ,b.day_number -- between 1 and 31
  ,b.number_of_hours
  from users a
  inner join work b on a.id = b.person_id
) pivot (-- pibot clouse
  sum(number_of_hours)
  for day_number in (1,2, ..., 31)
)