SQL 服务器日期时间转换功能等同于 postgresql (pivotal hawq)

SQL Server datetime convert function equivalent to postgresql (pivotal hawq)

我们在 SQL Server 2012 中有以下 SQL 脚本。我们将在数据库转换时在 postgresql (HAWQ 1.3.1) 中编写类似的脚本

SELECT * 
FROM tablename_1 
LEFT OUTER JOIN
     (SELECT 
          SUM(b.OrderValue) AS OrderValue, b.OrderDate, b.Description 
      FROM 
          (SELECT * 
           FROM tablename_2 rcd
           LEFT JOIN 
                (SELECT Distinct 
                     afv.Item, afv.Description, afd.KeyField
                 FROM tablename_3 afd
                 JOIN tablename_3 afv ON afv.FormType = afd.FormType 
                                      AND afv.FieldName = afd.FieldName 
                                      AND afv.Item = afd.AlphaValue
                 WHERE
                      afd.FormType = 'CUS'
                      AND afd.FieldName = 'COR002') a ON a.KeyField = rcd.Customer 
           WHERE
               OrderDate >= CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()), 101)) b 
    GROUP BY
        b.OrderDate, b.Description) c ON rtr.CorpAcctName = c.Description

我们尝试编写了以下脚本:

以上脚本编译成 postgresql(版本 HAWQ 1.3.1)

SELECT * from tablename_1  rtr LEFT OUTER JOIN
(SELECT SUM(b."OrderValue") as OrderValue,b."OrderDate", b."Description" from
(SELECT *  from tablename_2 rcd
LEFT JOIN 
( SELECT Distinct afv."Item", afv."Description", afd."KeyField"
FROM tablename_2 afd
  Join tablename_3 afv on afv."FormType" = afd."FormType" and afv."FieldName"=afd."FieldName" and afv."Item"=afd."AlphaValue"
Where   afd."FormType" = 'CUS'and afd."FieldName" = 'COR002') a
ON a."KeyField" =rcd."Customer" where "OrderDate">=TO_CHAR((CURRENT_DATE -(CURRENT_DATE-INTERVAL '1 DAY)) ,'MM-DD-YYYY')) b 
group by b."OrderDate", b."Description") c
on rtr."CorpAcctName"=c."Description"

也试过:

**

**

i wanted to achieve first day of month from my current_date

所以您想要在当月开始之后创建的所有内容。

一个简单的

where "OrderDate" >= date_trunc('month', current_date)

会的。

关于date_trunc()方法的详细信息可以在手册中找到:
http://www.postgresql.org/docs/current/static/functions-datetime.html


您应该了解您的表达式 TO_CHAR((CURRENT_DATE -(CURRENT_DATE-INTERVAL '1 DAY')) ,'MM-DD-YYYY') 在做什么,以便您将来避免该错误:

首先:current_date - interval '1 day'date 减去 intervalwhich yields a timestamp:"yesterday" 在 00:00:00

然后从今天的日期中减去它,所以 current_date - timestamp '2015-11-13 00:00:00.0'(如果今天是 2015 年 11 月 14 日)。

这会产生一个 interval0 years 0 mons 1 days 0 hours 0 mins 0.00 secs

然后将 interval 传递给 to_char() 函数,该函数格式化传递的间隔。因为它只有“1 天”,没有年月,所以应用格式字符串 'MM-DD-YYYY' 的结果确实会产生 00-01-0000

然后您将此 字符 值与真实值 date 进行比较 - 这也是您不应该做的事情。


您真的应该摆脱那些可怕的引用标识符。他们比他们值得的麻烦多得多