如何从一个表转换数据类型以匹配另一个表的数据类型?

时间:2017-03-20 05:33:08

标签: sql amazon-redshift

我有两个数据集共享所有相同的列标题,但不是相同的数据类型。一个数据集包含历史销售额,另一个包含每日销售额。每日销售表的数据类型每天都在变化,具体取决于某些列是否包含值。

我希望每日销售数据类型与历史销售数据类型匹配,但是当数据类型已匹配时收到错误,因为我强制NULL值为空白记录。

以下是我的查询示例:

SELECT FileType,
       ACDealerID,
       DealNumber,
       CustomerNumber,
       CAST(NULLIF(Birthdate, '') AS DATE) AS Birthdate,
       CAST(NULLIF(RetailPayment, '') AS DECIMAL) AS RetailPayment
FROM Daily_Sales

UNION ALL

SELECT FileType,
       ACDealerID,
       DealNumber,
       CustomerNumber,
       Birthdate,
       RetailPayment
FROM Historicals

以下是我今天收到的错误消息

  

错误:类型为date的输入语法无效:“”

我知道错误是由于每日销售中的Birthdate字段已经是DATE数据类型,但有时候Birthdate字段是一个带有空值的字符串,我需要我的查询来解释这些变化到了一天。

2 个答案:

答案 0 :(得分:0)

您需要使用CASE来阻止数据库尝试转换空字符串。

CASE WHEN Birthdate IS NULL THEN NULL ELSE CAST(Birthdate AS DATE) END AS Birthdate,

答案 1 :(得分:0)

您是正确的,空字符串无法转换为日期。但是(遗憾地命名)NULLIF如果两个值匹配则返回第一个值,否则返回NULL,在你的情况下,当你想返回NULL时返回空字符串。

与Joe Harris所说的类似,您可以使用CASE

Sub SendEmail()
    Dim OutApp As Outlook.Application
    Dim OutMail As Outlook.MailItem
    Dim strbody As String

    Dim olInsp As Outlook.Inspector
    Dim document As Word.document
    Dim oRng As Excel.Range

    Set OutApp = New Outlook.Application
    Set OutMail = OutApp.CreateItem(olMailItem)

    With OutMail
        .To = "...@...com"
        .CC = ""
        .BCC = ""
        .Subject = Cells(3, 2)
        .Display
        Set olInsp = .GetInspector

        If olInsp.IsWordMail And olInsp.EditorType = olEditorWord Then
            Set document = olInsp.WordEditor
            Set oRng = Range("A1:B2") ' The range you wish to copy into the document
            oRng.Copy ' Loads info to clipboard
            ' Write the range into the first paragragh of the word document.
            document.Paragraphs(1).Range.PasteExcelTable False, False, True

            ' Example how to write to the end of the email.
            Dim p As Word.Paragraph
            Set p = document.Paragraphs.Add
            p.Range.Text = "test"
        End If

    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

NVL|COALESCE应该是NULLIF的反转,但不能做你想做的事。

注意:NULL和已经是DATE类型的值将很快转换为DATE。

(CASE WHEN Birthdate='' THEN NULL ELSE Birthdate END)::DATE AS Birthdate,