计算由union合并的两个查询的两个日期之间的天差

时间:2015-03-24 11:23:52

标签: sql sql-server date union union-all

我有两个查询,它们之间都有一个联合。我试图计算两个日期之间的差异,其中一个在第一个查询中,另一个在第二个查询中。

第一个查询中的第一个日期是t0.duedate,第二个查询中的第二个日期是t0.docdate。 我将在水晶报告中使用此查询,其中我将基于字段t0来设置resualt的条件。[u_a_id]在两个查询中都可用 现在的resualt就像这样

 DocENTRY   slpname DocNum  SeriesName  Series  DocType DocDate DocdueDate  CardCode    CardName    DocTotal    u_a_id  type
1               -   1   Primary 12  C   2006-01-31 00:00:00.000 2006-01-31 00:00:00.000 C20000  Norm Thompson   14023.800000    NULL    A/R INCOMING PAYMENT

323 Sales Manager   323 Primary 1   I   2012-06-09 00:00:00.000 2012-07-09 00:00:00.000 C20000  Maxi-Teq    4253.250000 NULL    A/R INVOICE

我需要再增加一列需要天差,这将计算两个日期之间的差异" 2012-07-09 - 2006-01-31"像这样:

Days Difference 
 1921 Day

以下是查询:

 SELECT DISTINCT
        t0.[DocENTRY] ,
        oslp.slpname ,
        t0.[DocNum] ,
        nnm1.SeriesName ,
        t0.[Series] ,
        t0.[DocType] ,
        t0.[DocDate] ,
        t0.[DocdueDate] ,
        t0.[CardCode] ,
        t0.[CardName] ,
        t0.[DocTotal] ,
        t0.[u_a_id] ,
        'A/R INVOICE' AS type
FROM    OINV t0
        INNER JOIN NNM1 ON nnm1.series = t0.Series
        INNER JOIN OSLP ON oslp.slpcode = t0.slpcode
WHERE   t0.DOCSTATUS = 'C'
UNION ALL
SELECT DISTINCT
        t0.[DocENTRY] ,
        '-' AS slpname ,
        t0.[DocNum] ,
        nnm1.SeriesName ,
        t0.[Series] ,
        t0.[DocType] ,
        t0.[DocDate] ,
        t0.[DocdueDate] ,
        t0.[CardCode] ,
        t0.[CardName] ,
        t0.[DocTotal] ,
        t0.[u_a_id] ,
        'A/R INCOMING PAYMENT' AS type
FROM    orct t0
        INNER JOIN NNM1 ON nnm1.series = t0.Series
ORDER BY t0.[CardCode]

1 个答案:

答案 0 :(得分:0)

通过使用嵌套查询将第二个查询的日期带到第一个查询,然后在CR中制作了一个公式来计算日期之间的差异, 更新后立即查询:

select distinct T0.[DocENTRY],

T0.[DocNum],nnm1.SeriesName, T0.[Series],oslp.SlpName,

 T0.[DocDate] as 'Invoice Date',T0.[DocDueDate], T0.[CardCode], 

 T0.[CardName],  T0.[DocTotal], T0.[Comments], 

  'A/R invoice' as type, t0.U_A_ID,
  (select docdate from ORCT where orct.U_A_ID = t0.U_A_ID)
   as PaymentDt


from oinv t0 

inner join  NNM1 on nnm1.series =t0.Series 

inner join OSLP on oslp.SlpCode =t0.SlpCode

where T0.DocStatus ='c'

union all 

select distinct T0.[DocENTRY],

T0.[DocNum],nnm1.SeriesName, T0.[Series],

'_' AS SlpName,  T0.[DocDate], 

T0.[DocDueDate] AS 'Payment Due Date',

 T0.[CardCode], T0.[CardName],  T0.[DocTotal],

  T0.[Comments], 

 'A/R Incoming Payment' as type, t0.U_A_ID , getdate() as paymentdt

from ORCT t0 


inner join  NNM1 on nnm1.series =t0.Series 


order by t0.CardCode,t0.u_A_id

CR中使用的公式为:

 DATEDIFF("d",{Command.PaymentDt},{Command.DocDueDate})