具有条件的SUBSTRING

时间:2017-07-14 03:52:51

标签: sql-server substring conditional-statements

我希望这个+3适用于payterm,如果小于45。

我目前的代码是:

SELECT 
    [course_title],
    sblPOAmount,
    SBLInvoiceDate,
    paymentTerm,
    DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) 
FROM 
    [A_Sys].[dbo].[Eventtbl]
WHERE 
    DATENAME(MONTH, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) = 'June' 
    AND DATENAME(YEAR, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) = '2017'

WITH SUM语句(摘要)

SELECT
SUM(sblPOAmount) AS totalPOAmt,
case 
    when paymentTerm = '45 Days'
    then DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) 
    else DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 0, SBLInvoiceDate))
end 
FROM 
[A_Sys].[dbo].[Eventtbl] 
WHERE DATENAME(MONTH, DATEADD(day,SUBSTRING(paymentTerm, 1, 2)+3,SBLInvoiceDate))='June' 
AND DATENAME(YEAR, DATEADD(day,SUBSTRING(paymentTerm, 1, 2)+3,SBLInvoiceDate))='2017'
Group By paymentTerm,SBLInvoiceDate

目前,我无法按照

分组 #

电流输出: + ----- + --- + | 10.60 | 23 | | 0.00 | 24 | | 10.50 | 14 | + --------- +

预期产量: 只是21.10

1 个答案:

答案 0 :(得分:1)

您正在寻找案例陈述......

SELECT 
    [course_title],
    sblPOAmount,
    SBLInvoiceDate,
    paymentTerm,
    case 
        when paymentTerm < 45 then DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) 
        else DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2), SBLInvoiceDate))
    end
FROM 
    [A_Sys].[dbo].[Eventtbl]
WHERE 
    DATENAME(MONTH, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) = 'June' 
    AND DATENAME(YEAR, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) = '2017'

基于修改

SELECT 
    [course_title],
    sum(sblPOAmount),
    SBLInvoiceDate,
    paymentTerm,
    case 
        when paymentTerm < 45 then DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) 
        else DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2), SBLInvoiceDate))
    end
FROM 
    [A_Sys].[dbo].[Eventtbl]
WHERE 
    DATENAME(MONTH, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) = 'June' 
    AND DATENAME(YEAR, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) = '2017'
GROUP BY
    [course_title],
    SBLInvoiceDate,
    paymentTerm,
    case 
        when paymentTerm < 45 then DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2) + 3, SBLInvoiceDate)) 
        else DATENAME(Day, DATEADD(day, SUBSTRING(paymentTerm, 1, 2), SBLInvoiceDate))
    end