Postgres column does not exist

后端 未结 1 1376
忘了有多久
忘了有多久 2020-12-22 03:40

Someone else wrote a SQL Server query which worked, and I have the job of porting it over to Postgres.

I don\'t really know either database beyond the very basic SQ

相关标签:
1条回答
  • 2020-12-22 04:10

    Edited: The quoted capitalization is tanking the query. In the output of the second failure below you can see Postgres does not like the upper case. It has a habbit of lowercaseing everything unless you force with " quotes.

    --fails
    select a
    from
    (select 1 as "A") as t;
    
    --fails
    select A
    from
    (select 1 as "A") as t;
    
    --works
    select "A"
    from
    (select 1 as "A") as t;
    
    psql:new.sql:5: ERROR:  column "a" does not exist
    LINE 1: select a
                   ^
    psql:new.sql:10: ERROR:  column "a" does not exist
    LINE 1: select A
                   ^
     A 
    ───
     1
    (1 row)
    
    
    select ...
    timeloggedToday.date_logged "DATE_LOGGED_TODAY",
    -- should be: timeloggedToday."DATE_LOGGED" "DATE_LOGGED_TODAY",
    
    ...
    
    LEFT JOIN
      (SELECT app_user.lower_user_name,
              to_char(startdate, '%Y-%m-%d') AS "DATE_LOGGED",
              Sum(timeworked) / 3600 "TIME_IN_HOURS",
              startdate - Now() "DIFFERENCE_DAYS"
       ...
      ) timeloggedToday ON timeloggedToday.lower_user_name = users.author;
    

    I would think about getting rid of the capitalization and quotes. It just going to cause headaches. As a side note, you could write the left join just once by:

    -- instead of enumerating each possible interval  
    WHERE to_char(Now() - INTERVAL '8 days', '%Y-%m-%d') < to_char(startdate, '%Y-%m-%d')
    -- select the interval
    now()::date - start_date as diff
    -- then build up your columns like:
    case(case when diff=0 then date_logged else null end) as date_logged_today
    case(case when diff=1 then date_logged else null end) as date_logged_yesterday
    -- and so on ...
    

    Also you could make

    CASE
       WHEN Ifnull(timeloggedToday.time_in_hours, 0) = 0 THEN 'No Time Logged'
       WHEN timeloggedToday.time_in_hours < 3.0 THEN 'User has not logged sufficient time' 
       ELSE 'user has logged sufficient time'
     END "STATUS_TODAY",
    

    into a function to get rid of the tedious redundancy.

    0 讨论(0)
提交回复
热议问题