簡體   English   中英

在MySQL中圍繞日期列引用表

[英]PIvoting table around date column in Mysql

我正在嘗試旋轉這張桌子

timetableId, assignmentId, dateChecked, hoursWorked
          1,       11,      2017-09-10,     5
          2,       12,      2017-09-10,     5
          3,       13,      2017-09-11,     8
          4,       11,      2017-09-11,     8
          5,       12,      2017-09-11,     8
          6,       13,      2017-09-10,     8

以便顯示

assignmentId, tenth,  eleventh
          11,      5,   8
          12,      5,   8
          13,      0,   8

我有以下基於該網站上的教程的代碼http://stratosprovatopoulos.com/web-development/mysql/pivot-a-table-in-mysql/

create view timetable_extended as (
 select
    timetables.assignmentId,
    case when dateChecked = '10-09-2017' then timetables.hoursWorked end as tenth,
    case when dateChecked = '11-09-2017' then timetables.hoursWorked end as eleventh
   from timetables
);

create view timetable_extended_Pivot as (
 select
   assignmentId,
   sum(tenth) as tenth,
   sum(eleventh) as eleventh
 from timetable_extended
 group by assignmentId
);

create view timetable_extended_Pivot_Pretty as (
  select 
  assignmentId, 
  coalesce(tenth, 0) as tenth, 
  coalesce(eleventh, 0) as eleventh
 from timetable_extended_Pivot
);

但是由於某種原因,第一個視圖將所有值都返回為null,而不是執行應做的事情-即

    assignmentId, tenth,  eleventh
          11,      5,       NULL
          11,      NULL     8
          12,      5,       NULL
          12,      NULL     8
          13,      NULL,    8

我究竟做錯了什么? 我需要將日期轉換為字符串嗎?

我已經嘗試過使用與主列相同的代碼和字符串,並且效果很好

create table User_Items
(
 Cust_Names varchar(10),
 Item_Type  varchar(50),
 Item_Amount float
 );

insert into User_Items values
 ('Alison', 'Computer', 345.39),
 ('Alison', 'Monitor', 123.45),
 ('Jason', 'Computer', 435.34),
 ('Jason', 'Monitor', 158.23),
 ('Jason', 'Software', 243.54);

 create view User_Items_Extended as (
  select
   User_Items.Cust_Names,
   case when Item_Type = "Computer" then Item_Amount end as Computer,
   case when Item_Type = "Monitor" then Item_Amount end as Monitor,
   case when Item_Type = "Software" then Item_Amount end as Software
  from User_Items
 );

create view User_Items_Extended_Pivot as (
 select
  Cust_Names,
  sum(Computer) as Computer,
  sum(Monitor) as Monitor,
  sum(Software) as Software 
  from User_Items_Extended
 group by Cust_Names
);

create view User_Items_Extended_Pivot_Pretty as (
 select 
  Cust_Names, 
  coalesce(Computer, 0) as Computer, 
  coalesce(Monitor, 0) as Monitor, 
  coalesce(Software, 0) as Software
from User_Items_Extended_Pivot
);

問題在這里:

case when dateChecked = '10-09-2017'

使用YYYY-MM-DD格式進行日期比較,而不要使用MM-DD-YYYY。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM