TSQL Datediff(dd,MAX(p_effdt),CURRENT_TIMESTAMP)

Hi,
OBJECTIVE: for a group of clients, report the average number of days in which they have been enrolled in a given program.
PROBLEM: the clients are often dropped and later re-enrolled in our programs.  So, I want to use only the most recent enrollment date for each client.  And then calculate an average number of days enrolled.
The data looks like this:
c_id p_effdt p_lapdt
123456 12/19/2013 NULL
234567 11/10/2003 12/23/2003
345678 11/25/2010 NULL
345678 12/16/2010 4/29/2010
456789 11/11/2004 11/30/2004
456789 11/13/2003 12/29/2003
Of course, this: Datediff(dd,MAX(p_effdt),CURRENT_TIMESTAMP)
results in the error: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
DECLARE @LastProgramEffectiveDate DATETIME
SET @LastProgramEffectiveDate = MAX(program.p_effdt)
SELECT AVG(Datediff(dd,@LastProgramEffectiveDate,CURRENT_TIMESTAMP))
FROM events INNER JOIN program ON events.e_case_no = program.c_id
Error: The multi-part identifier "program.p_effdt" could not be bound.
So that SQL query is not the way to go.  What is the best way to accomplish the above defined objective?
Thank you.
Alpineer8

It's not clear what you are doing.  When you do a MAX(), you only get one value per group (or if your query doesn't have a GROUP BY, one value per query).  It makes no sense to do an AVG of one value - it is just that value.  So, I suspect
there is something more complicated about what you are doing.  Could you provide a more complete description of what you are doing, and sample tables and sample data and the result you want from that sample data?  Also, let us know the release of
SQL Server you are using.  Doing that usually lets us quickly provide you with a helpful answer.
Tom

Similar Messages

  • The SELECT permission was denied on the object 'syscategories', database 'msdb', schema 'dbo'.

    Hi all,
    I have a single select statement to monitor JOB status at database msdb, it works perfectly at versions 2000, 2005 and 2008 but in version 2012 got denied access to views syscategories, sysjobactivity, sysjobhistory, sysjobs and sysjobsteps even having applied
    "grant select on" to user (principals) at database msdb.
    Anyone have seen this and found an solution?
    --- SQL Server Version
    Microsoft SQL Server 2012 (SP1) - 11.0.3000.0 (X64)
        Oct 19 2012 13:38:57
        Copyright (c) Microsoft Corporation
        Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
    --- My Query
    set nocount on
    select x.job_name, x.job_status, x.monitor_status from (
    select j.name job_name
         , case
             when datediff(minute,s.login_time,current_timestamp) >= 8
                then 'In progress (more than 8h) '
             when datediff(minute,s.login_time,current_timestamp) >= 24
                then 'In progress (more than 24h) '
             else 'In progress'
           end job_status
         , case
             when datediff(minute,s.login_time,current_timestamp) >= 8
                then 8 -- 'In progress (more than 8h) '
             when datediff(minute,s.login_time,current_timestamp) >= 24
                then 9 -- 'In progress (more than 24h) '
             else 7 -- 'In progress'
           end monitor_status
      from sys.dm_exec_sessions s
             join msdb.dbo.sysjobs j
                on master.dbo.fn_varbintohexstr(convert(varbinary(16), j.job_id))COLLATE Latin1_General_CI_AI
                 = substring(replace(s.program_name, 'SQLAgent - TSQL JobStep (Job ', ''), 1, 34)
             inner join msdb.dbo.syscategories c
                on c.category_id = j.category_id
     where s.program_name like '%SQLAGENT - TSQL JOBSTEP%'
       and c.name like 'REPL-%'
    union all
    select j.name
         , case
              when datediff(minute,current_timestamp,ja.next_scheduled_run_date) <= -10
                 then 'Delayed'
              else
                 case jh.run_status
                    when 0 then
                       case when lower(left(j.name,8)) = 'uoldiveo'
                          then 'Failed (admin)'
                          else 'Failed'
                       end
                    when 1 then 'Succeeded'
                    when 2 then 'Retry'
                    when 3 then
                       case when lower(left(j.name,8)) = 'uoldiveo'
                          then 'Cancelled (admin)'
                          else 'Cancelled'
                       end
                    when 4 then 'In progress'
                 end
           end
         , case
              when datediff(minute,current_timestamp,ja.next_scheduled_run_date) <= -10
                 then 0 -- Delayed
              else
                 case jh.run_status
                    when 0 then
                       case when lower(left(j.name,8)) = 'uoldiveo'
                          then 1 -- 'Failed (admin)'
                          else 2 -- 'Failed'
                       end
                    when 1 then 3 -- 'Succeeded'
                    when 2 then 4 -- 'Retry'
                    when 3 then
                       case when lower(left(j.name,8)) = 'uoldiveo'
                          then 5 -- 'Cancelled (admin)'
                          else 6 -- 'Cancelled'
                       end
                    when 4 then 7 -- 'In progress'
                 end
           end
      from (msdb.dbo.sysjobactivity ja left join msdb.dbo.sysjobhistory jh on ja.job_history_id = jh.instance_id)
           join msdb.dbo.sysjobs j on ja.job_id = j.job_id
     where ja.session_id=(select max(session_id) from msdb.dbo.sysjobactivity where job_id = ja.job_id)
            and j.enabled = 1
            and jh.run_status <= 3
    ) x

    I was able to run the below without problems on SQL 2012:
    USE master
    CREATE LOGIN ove WITH PASSWORD = 'ÖLKJLKJ?="#'
    GRANT VIEW SERVER STATE TO ove
    go
    USE msdb
    go
    CREATE USER ove
    GRANT SELECT ON syscategories TO ove
    GRANT SELECT ON sysjobactivity TO ove
    GRANT SELECT ON sysjobhistory TO ove
    GRANT SELECT ON sysjobs TO ove
    GRANT SELECT ON sysjobsteps TO ove
    go
    EXECUTE AS LOGIN = 'ove'
    -- your query here
    REVERT
    go
    DROP USER ove
    go
    USE tempdb
    go
    DROP LOGIN ove
    Have you checked that there is no active DENY in force?
    Rather than granting these permissions, you could package this in a stored procedure that you signed with a certificate and then grant a login and user create from the certificate the required permissions. I discuss this technique in detail in an article
    on my web site:
    http://www.sommarskog.se/grantperm.html
    (But certs will not help you against DENY.)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • B1_JournalTransSourceView and JDT1 regarding

    Dear Friends,
    Can you please clarify the significance of the following two lines in the code given below? I have commented these two lines as I am getting any difference by enabling or disabling it.
    --               AND (T3.[TransType] <> N'I'  OR  (T3.[TransType] = N'I'   
    --               AND T3.[InstlmntID] = T0.[SourceLine] ))
    Here, basically the B1_JournalTransSourceView is primary concern and it's exact behavior.
    GO
    /****** Object:  StoredProcedure [dbo].[AgeingForCustomer]    Script Date: 03/15/2011 23:07:05 ******/
    --EXEC AgeingForCustomer '2000-04-01 00:00:00','2011-04-03 00:00:00', 'C99998'
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    alter PROCEDURE [dbo].[AgeingForCustomer](
    @DateTo          Datetime                    --Mandotary -Y
    ,@DateFrom          Datetime                    --Mandotary -Y
    ,@CardCode varchar(20)
    AS
    SELECT
    T0.[TransId]
    ,MAX(T2.CardType) 'BP Type'
    ,MAX(T0.[ShortName])'BP.Code'
    ,MAX(T2.[CardName])'BP.Name'
    ,MAX(T2.[Balance])'Balance'
    ,MAX(T0.[TransType])'Trans.Type'
    ,MAX(T0.[Account])'GL Account'
    ,MAX(T4.AcctName) 'GL Name'
    ,MAX(T0.[BaseRef])'Doc.No.'
    ,MAX(T0.[RefDate])'Posting Date'
    ,MAX(T0.[DueDate])'Due Date'
    ,MAX(T0.[TaxDate])'Doc.Date'
    ,MAX(T3.[NumAtCard])'BP Ref.No.' -- Customer / Vendor Ref. No. in the marketting docs
    ,DATEDIFF(Day,T0.DueDate,current_timestamp )'Tot.Due Age'
    ,SUM(T0.[Debit]) + SUM(T0.[Credit])'Org.Amt.'
    ,SUM(T0.[SYSDeb]) + SUM(T0.[SYSCred])'Sys.Org.Amt.'
    ,MAX(T0.[BalDueDeb])- MAX(T0.[BalDueCred]) 'Bal.Amt.'
    ,MAX(T0.[BalScDeb]) - MAX(T0.[BalScCred])'Sys.Bal.Amt.'
    ,(Select MainCurncy from OADM) 'Main Curr.'
    ,(Select SysCurrncy from OADM) 'Sys.Curr.'
    ,MAX(T2.[Currency])'BP Curr.'
    ,MAX(T0.[FCCurrency])'FC Curr.'
    ,MAX(T5.U_Name) 'Crteated By'
    ,MAX(T0.[LineMemo])'Journal Remark'
    ,MAX(T0.[Project])'Project'
    ,MAX(T2.[PymCode])'Pmt.Code'
    ,MAX(T3.[BlockDunn])'Doc. Block Dunning' --- "Bloc&k Dunning Letters" of marketting docs (logistics tab), the same field in OJDT table does not work.
    ,MAX(T2.[BlockDunn])'Cust. Block Dunning' --- "Bloc&k Dunning Letters" of the customer
    ,MAX(T3.[DunnLevel])'Dunning Level'
    ,MAX(T2.[DunTerm])'Dunning Term'
    FROM
    [dbo].[JDT1] T0  -- Journal table  - row
    INNER JOIN [dbo].[OJDT] T1 ON T1.[TransId] = T0.[TransId] -- Jounal table - header
    INNER JOIN [dbo].[OUSR] T5 ON T1.UserSign = T5.UserID
    INNER JOIN [dbo].[OCRD] T2 ON T2.[CardCode] = T0.[ShortName]   
    INNER JOIN [dbo].[OACT] T4 ON T0.[Account] = T4.AcctCode
    LEFT JOIN [dbo].[B1_JournalTransSourceView] T3 ON T3.[ObjType] = T0.[TransType]
                   AND T3.[DocEntry] = T0.[CreatedBy]
    --               AND (T3.[TransType] <> N'I'  OR  (T3.[TransType] = N'I'   
    --               AND T3.[InstlmntID] = T0.[SourceLine] ))
    WHERE
    T0.RefDate BETWEEN CONVERT(VARCHAR, @DateTo, 112)  AND CONVERT(VARCHAR, @DateFrom, 112)
    AND T2.CardType='C'
    AND T2.Balance <> 0
    AND (T0.[BalDueCred] <> T0.[BalDueDeb] OR T0.[BalFcCred] <> T0.[BalFcDeb])
    AND T0.ShortName = @CardCode
    GROUP BY T0.TransId,T0.Line_ID,T0.RefDate,T0.DueDate   
    ORDER BY T0.RefDate

    https://websmp109.sap-ag.de/~form/sapnet?_SHORTKEY=01100035870000705857&_SCENARIO=01100035870000000183&_ADDINC=011000358700001192682007E&
    check link or
    Go to Channel.sap.com
    login to channel partner portal using suid and pwd.
    Go to solutions---Then SAP Business one.
    on the left hand side
    click on link Product availability.
    U will get the data you want
    regards,
    Neetu

  • Open aging report

    This report has been extended from an existing query that has been posted on this forum. 
    This report is an aging report for ALL trasnactions, both open and closed.
    Is it possible to modify this query to report on OPEN / unreconciled trasnactions only?
    select T0.shortname,T2.cardcode 'Customer Code',T2.cardname 'Name',T2.U_BU, T2.U_DEPT, sysdeb 'Debit Amount',syscred 'Credit Amount',
    case T0.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    T1.BaseRef'Trans #',
    case T0.transtype
    when '13' then
    (Select Comments from OINV where OINV.Transid=T1.Transid)
    else '-'
    end 'Inv.Rem.',
    (Select SeriesName From NNM1 Where Series=T1.DocSeries and ObjectCode=T0.TransType)'Series',
    T0.Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), T0.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), T0.duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), T0.taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "0-30 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30
    and (datediff(dd,T0.refdate,current_timestamp))+1< 61)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60
    and (datediff(dd,T0.refdate,current_timestamp))+1< 91)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "61 to 90 days",
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 90
    then
    case
    when syscred= 0 then sysdeb
    when sysdeb= 0 then syscred * - 1
    end
    end "90 + days"
    from JDT1 T0
    Inner Join OJDT T1 On T1.TransId=T0.TransId
    left outer join
    OCRD T2 ON T2.cardcode =T0.shortname where
    T2.cardtype = 'c' and T0.intrnmatch = '0' and
    T2.U_Bu = %0and T2.U_Dept = %1
    ORDER BY T2.CARDCODE, T0.taxdate
    Thanks in advanced Lisa

    Thanks for the feedback Jule - I have changed the query as is as below
    Unfortunately,  the query is still reporting ALL transactions not just unreconciled transations.
    Would be grateful for any assistance.
    Cheers Lisa
    select T0.shortname,T2.cardcode 'Customer Code',T2.cardname 'Name',T2.U_BU, T2.U_DEPT, balscdeb 'Debit Amount',balsccred 'Credit Amount',
    case T0.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    T1.BaseRef'Trans #',
    case T0.transtype
    when '13' then
    (Select Comments from OINV where OINV.Transid=T1.Transid)
    else '-'
    end 'Inv.Rem.',
    (Select SeriesName From NNM1 Where Series=T1.DocSeries and ObjectCode=T0.TransType)'Series',
    T0.Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), T0.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), T0.duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), T0.taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31
    then
    case
    when balsccred <> 0 then balsccred * - 1
    else balscdeb
    end
    end "0-30 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30
    and (datediff(dd,T0.refdate,current_timestamp))+1< 61)
    then
    case
    when balsccred <> 0 then balsccred * - 1
    else balscdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60
    and (datediff(dd,T0.refdate,current_timestamp))+1< 91)
    then
    case
    when balsccred <> 0 then balsccred * - 1
    else balscdeb
    end
    end "61 to 90 days",
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 90
    then
    case
    when balsccred= 0 then balscdeb
    when balscdeb= 0 then balsccred * - 1
    end
    end "90 + days"
    from JDT1 T0
    Inner Join OJDT T1 On T1.TransId=T0.TransId
    left outer join
    OCRD T2 ON T2.cardcode =T0.shortname where
    T2.cardtype = 'c' and
    T2.U_Bu = [%0]and T2.U_Dept = [%1]
    ORDER BY T2.CARDCODE, T0.taxdate

  • Query Help required to Connect JDT1 with OINV tables

    Dear Experts,
    I have the following query which gives me the customer ageing report. I want some addtional fields from the OINV table and the document numbering table like Document Series Name, AR Invoice document Number,AR invoice remarks, BP Projects Number ( filled in accounting tab in BP projects) and in the query in Reference 1 column its giving the Invoice Numbers as posted in the Journal but for manual Journal Entries it not giving the Journal Number which I also want to be shown in Ref 1 or a seperat field.
    The Query is as under :
    select OCRD.cardcode 'Supplier Code',OCRD.cardname 'Name',sysdeb 'Debit Amount',syscred 'Credit Amount',
    case JDT1.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,refdate,current_timestamp))+1 < 31
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "0-30 days",
    case when ((datediff(dd,refdate,current_timestamp))+1 > 30
    and (datediff(dd,refdate,current_timestamp))+1< 61)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,refdate,current_timestamp))+1 > 60
    and (datediff(dd,refdate,current_timestamp))+1< 91)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "61 to 90 days",
    CASE
    when (DATEDIFF(dd,refdate,current_timestamp))+1 > 90
    then
    case
    when syscred= 0 then sysdeb
    when sysdeb= 0 then syscred * - 1
    end
    end "90 + days"
    from JDT1,OCRD where JDT1.shortname = OCRD.cardcode and cardtype = 'c' and intrnmatch = '0'
    ORDER BY OCRD.CARDCODE, taxdate
    Would appreciate if you can help me to get a solution in it.
    Regards,
    Kamlesh

    Dear Gordon,
    While executing the followings modified query it giving an error of
    Incorrect Syntax near the keyword 'to' and incorrect Syntax near 'Series'
    the query is as under :
    {select OCRD.cardcode 'Supplier Code',OCRD.cardname 'Name',sysdeb 'Debit Amount',syscred 'Credit Amount',
    case l.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    j.BaseRef'Trans #',
    case l.transtype
    when '13' then
    (Select Comments from OINV where OINV.Transid=j.Transid)
    else '-'
    end 'Inv.Rem.',
    (Select SeriesName From NNM1 Where Series=j.DocSeries and ObjectCode=l.TransType)'Series',
    to
    (Select Isnull(SeriesName, 'Manual') From NNM1 Where Series=j.DocSeries and ObjectCode=l.TransType)'Series',
    l.Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), l.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), l.duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), l.taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,l.refdate,current_timestamp))+1 < 31
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "0-30 days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 30
    and (datediff(dd,l.refdate,current_timestamp))+1< 61)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 60
    and (datediff(dd,l.refdate,current_timestamp))+1< 91)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "61 to 90 days",
    CASE
    when (DATEDIFF(dd,l.refdate,current_timestamp))+1 > 90
    then
    case
    when syscred= 0 then sysdeb
    when sysdeb= 0 then syscred * - 1
    end
    end "90 + days"
    from JDT1 l
    Inner Join OJDT j On j.TransId=l.TransId
    ,OCRD where l.shortname = OCRD.cardcode and cardtype = 'c' and intrnmatch = '0'
    ORDER BY OCRD.CARDCODE, l.taxdate}
    Regards,
    Kamlesh

  • Ageing Report

    Dear Experts
    can anybody please help me in getting ageing report project wise . We already have the ageing report Debtors or Creditors wise
    in the system but i want the ageing report project wise
    warm regards
    anand

    Hi Rajshree
    Try this One for customers, hopefully you should then be able to amend it to the Supplier Version
    select T0.shortname,T2.cardcode 'Customer Code',T2.cardname 'Name', sysdeb 'Debit Amount',syscred 'Credit Amount',
    case T0.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    T1.BaseRef'Trans #',
    case T0.transtype
    when '13' then
    (Select Comments from OINV where OINV.Transid=T1.Transid)
    else '-'
    end 'Inv.Rem.',
    (Select SeriesName From NNM1 Where Series=T1.DocSeries and ObjectCode=T0.TransType)'Series',
    T0.Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), T0.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), T0.duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), T0.taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "0-30 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30
    and (datediff(dd,T0.refdate,current_timestamp))+1< 61)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60
    and (datediff(dd,T0.refdate,current_timestamp))+1< 91)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "60 to 90 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90
    and (datediff(dd,T0.refdate,current_timestamp))+1< 121)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "91 to 120 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 120
    and (datediff(dd,T0.refdate,current_timestamp))+1< 151)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "121 to 150 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 150
    and (datediff(dd,T0.refdate,current_timestamp))+1< 181)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "151 to 180 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 180
    and (datediff(dd,T0.refdate,current_timestamp))+1< 221)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "181 to 220 days",
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 220
    then
    case
    when syscred= 0 then sysdeb
    when sysdeb= 0 then syscred * - 1
    end
    end "220 + days"
    from JDT1 T0
    Inner Join OJDT T1 On T1.TransId=T0.TransId
    left outer join
    OCRD T2 ON T2.cardcode =T0.shortname where
    T2.cardtype = 'c' and T0.intrnmatch = '0'
    and (T0.BalDueCred  + T0.BalDueDeb) > 0
    ORDER BY T2.CARDCODE, T0.taxdate
    Kind regards
    Sean

  • Report to show average days it takes customers to pay their invoices

    I am wondering if there is a report in SAP that can help me determine the average days it takes customers to pay their invoices?

    Hi,
    Try this for date range
    declare @from as datetime
    Declare @to as datetime
    Set @from = /* Select min(T5.DocDate) from OINM T5 where T5.DocDate= */ '[%0]'
    Set @to = /* Select max(T6.DocDate) from OINM T6 where T6.DocDate= */ '[%1]'
    Select A.CardCode, A.CardName, Avg(A.Diff) [AverageDays] from
    (SELECT T2.[CardCode], T2.[DocEntry],
    T2.[CardName], max(T2.DocDate)[Inv], max(T0.DocDate) [Pay],
    datediff(dd, max(T2.DocDate), max(T0.DocDate)) [Diff]
    FROM ORCT T0 
    INNER JOIN RCT2 T1 ON T0.DocEntry = T1.DocNum
    inner join OINV T2 on T1.DocEntry = T2.DocEntry
    where T2.DocDate between @from and @to
    Group by  T2.[CardCode], T2.DocEntry, T2.[CardName]) A
    Group by A.CardCode, A.CardName
    Regards,
    Bala

  • AP aging?

    I have been asked to try and create a AP aging report. I have an AR Aging one complete. I did also try and change the tables around to get nothing but AP, but AR keeps coming into it.. Do any of you experts have a general starting query that I can use or knowledge on this to guide me to the right area? I am kinda of lost on how to retrieve some of the information from SAP that will fill in the blanks that the report needs. Here is what they are asking for:
    Vendor
    Project
    Open AP not due
    Open AP Due
    Down payments Done
    Still to be paid
    Then aged by month (Jan,Feb,March,etc...)
    Please, any help on this would be greatly appreciated.
    Thanks

    THANK YOU Gordon for replying......
    Here is what I am using for my AR that I changed to try and get AP from:
    SELECT    
                         OCRD.CardCode AS 'Customer Code', OCRD.CardName AS 'Customer Name',
                          OCRD.DebPayAcct AS 'Customer Control #',
                          CASE l.transtype WHEN '13' THEN 'AR Invoice' WHEN '14' THEN 'AR Credit Memo' WHEN '15' THEN 'Delivery Note' WHEN '18' THEN 'AP Invoice' WHEN
                           '19' THEN 'AP Credit Memo' WHEN '20' THEN 'Goods Reciept PO' WHEN '202' THEN 'Production Order' WHEN '24' THEN 'Incoming Payment' WHEN '25'
                           THEN 'Deposit' WHEN '30' THEN 'Journal Entry' WHEN '46' THEN 'Outgoing Payments' WHEN '58' THEN 'Stock Taking' WHEN '-3' THEN 'Profilt / Loss'
                           WHEN '60' THEN 'Issue for Production' WHEN '69' THEN 'Landed Costs' ELSE 'Other' END AS 'Doc Type', j.BaseRef AS 'Doc #',
                          CASE OPCH.DocStatus WHEN 'C' THEN 'CLOSED' WHEN 'O' THEN 'OPEN' ELSE CASE ORPC.DocStatus WHEN 'C' THEN 'CLOSED' WHEN 'O' THEN 'OPEN'
                           ELSE ' ' END END AS [Doc Status], l.TransId AS [Jrnl Entry #], CONVERT(VARCHAR(10), l.TaxDate, 101) AS 'Doc Date', CONVERT(VARCHAR(10),
                          l.DueDate, 101) AS 'Due Date', OPCH.NumAtCard AS 'BPs Ref. No.', CASE WHEN (OPCH.DocStatus = 'O') THEN (OPCH.DocTotal - OPCH.PaidToDate)
                          ELSE CASE WHEN (ORPC.DocStatus = 'O') THEN (ORPC.DocTotal - ORPC.PaidToDate) * - 1 ELSE CASE WHEN (l.Transtype = '24')
                          THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE '0' END END END END AS 'Open Balance Due',
                          DATEDIFF(dd, l.DueDate, CURRENT_TIMESTAMP) AS 'Days Due', CASE WHEN (DATEDIFF(dd, l.DueDate, CURRENT_TIMESTAMP))
                          <= 0 THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate) * - 1 ELSE CASE WHEN (l.TransType = '24')
                          THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE CASE WHEN (OPCH.DocStatus = 'O')
                          THEN OPCH.DocTotal - OPCH.PaidToDate ELSE '0' END END END END END AS [Current], CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP))
                          >= 1 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 31) THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate)
                          * - 1 ELSE CASE WHEN (l.TransType = '24') THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit)
                          ELSE CASE WHEN (OPCH.DocStatus = 'O') THEN (OPCH.DocTotal - OPCH.PaidToDate) ELSE '0' END END END END END AS [1 to 30 days],
                          CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 30 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 61)
                          THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate) * - 1 ELSE CASE WHEN (l.TransType = '24')
                          THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE CASE WHEN (OPCH.DocStatus = 'O')
                          THEN (OPCH.DocTotal - OPCH.PaidToDate) ELSE '0' END END END END END AS [31 to 60 days], CASE WHEN ((datediff(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) > 60 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 91) THEN CASE WHEN (l.TransType = '14')
                          THEN (ORPC.DocTotal - ORPC.PaidToDate) * - 1 ELSE CASE WHEN (l.TransType = '24') THEN (ORCT.NoDocSum * - 1)
                          ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE CASE WHEN (OPCH.DocStatus = 'O') THEN (OPCH.DocTotal - OPCH.PaidToDate)
                          ELSE '0' END END END END END AS [61 to 90 days], CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 90 AND (datediff(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) < 121) THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate)
                          * - 1 ELSE CASE WHEN (l.TransType = '24') THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit)
                          ELSE CASE WHEN (OPCH.DocStatus = 'O') THEN (OPCH.DocTotal - OPCH.PaidToDate) ELSE '0' END END END END END AS [91 to 120 days],
                          CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 120 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 181)
                          THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate) * - 1 ELSE CASE WHEN (l.TransType = '24')
                          THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE CASE WHEN (OPCH.DocStatus = 'O')
                          THEN (OPCH.DocTotal - OPCH.PaidToDate) ELSE '0' END END END END END AS [121 to 180 days], CASE WHEN ((datediff(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) > 180 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 366) THEN CASE WHEN (l.TransType = '14')
                          THEN (ORPC.DocTotal - ORPC.PaidToDate) * - 1 ELSE CASE WHEN (l.TransType = '24') THEN (ORCT.NoDocSum * - 1)
                          ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE CASE WHEN (OPCH.DocStatus = 'O') THEN (OPCH.DocTotal - OPCH.PaidToDate)
                          ELSE '0' END END END END END AS [181 to 1 Year], CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 365 AND (datediff(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) < 545) THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate)
                          * - 1 ELSE CASE WHEN (l.TransType = '24') THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit)
                          ELSE CASE WHEN (OPCH.DocStatus = 'O') THEN (OPCH.DocTotal - OPCH.PaidToDate) ELSE '0' END END END END END AS [1 Year to 1.5 Years],
                          CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 544 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 731)
                          THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate) * - 1 ELSE CASE WHEN (l.TransType = '24')
                          THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE CASE WHEN (OPCH.DocStatus = 'O')
                          THEN (OPCH.DocTotal - OPCH.PaidToDate) ELSE '0' END END END END END AS [1.5 Years to 2 Years], CASE WHEN (DATEDIFF(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) > 730 THEN CASE WHEN (l.TransType = '14') THEN (ORPC.DocTotal - ORPC.PaidToDate)
                          * - 1 ELSE CASE WHEN (l.TransType = '24') THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit)
                          ELSE CASE WHEN (OPCH.DocStatus = 'O') THEN (OPCH.DocTotal - OPCH.PaidToDate) ELSE '0' END END END END END AS [2 Years and Greater],
                          CASE l.transtype WHEN '13' THEN
                              (SELECT     Comments
                                FROM          OPCH
                                WHERE      OPCH.Transid = j.Transid) ELSE '-' END AS [Invoice Remarks]
    FROM         JDT1 AS l INNER JOIN
                          OJDT AS j ON j.TransId = l.TransId INNER JOIN
                          OCRD ON l.ShortName = OCRD.CardCode LEFT OUTER JOIN
                          ORCT ON l.TransId = ORCT.TransId LEFT OUTER JOIN
                          ORPC ON l.TransId = ORPC.TransId LEFT OUTER JOIN
                          OPCH ON l.TransId = OPCH.TransId
    WHERE     (OCRD.CardType = 'c') AND (l.BalScDeb <> l.BalScCred) AND (OCRD.Balance <> 0)
    ORDER BY  l.TaxDate

  • Customers recievable as of date

    Dear Experts,
    I have created this query for Customers Recievables, the problem that I am having is that it only shows the open invoices even if it was closed after the date in my parameter.
    my requirements is like the Built-In Customers Recievables Aging in SAP but with the remarks on each invoice on the end.
    here is the query i used:
    SELECT 'IN' "Invoice/Credit Notes", T0.[CardCode], T0.[CardName], T0.[DocDate], T0.[DocDueDate], T0.[DocNum],
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) < 30 then (T0.[DocTotal]-T0.[PaidToDate]) end as '0-30',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) BETWEEN 31 and 60 then (T0.[DocTotal]-T0.[PaidToDate]) end as '31-60',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) BETWEEN 61 and 90 then (T0.[DocTotal]-T0.[PaidToDate]) end as '61-90',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) BETWEEN 91 and 120 then (T0.[DocTotal]-T0.[PaidToDate]) end as '91-120',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) > 120 then (T0.[DocTotal]-T0.[PaidToDate]) end as '120',
    T0.[Comments] FROM OINV T0  INNER JOIN OCTG T1 ON T0.GroupNum = T1.GroupNum INNER JOIN OCRD T2 ON T0.CardCode = T2.CardCode INNER JOIN OCRG T3 ON T2.GroupCode = T3.GroupCode WHERE T0.[DocStatus] ='O' AND  T0.[DocDate] <=[%1] AND  T2.[Cardcode] = 'CCBARTES A/S'
    UNION ALL
    SELECT 'CN',T0.[CardCode], T0.[CardName], T0.[DocDate], T0.[DocDueDate], T0.[DocNum],
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) < 30 then -(T0.[DocTotal]-T0.[PaidToDate]) end as '0-30',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) BETWEEN 31 and 60 then -(T0.[DocTotal]-T0.[PaidToDate]) end as '31-60',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) BETWEEN 61 and 90 then -(T0.[DocTotal]-T0.[PaidToDate]) end as '61-90',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) BETWEEN 91 and 120 then -(T0.[DocTotal]-T0.[PaidToDate]) end as '91-120',
    CASE WHEN DATEDIFF(DAY, T0.DocDueDate, [%1]) > 120 then -(T0.[DocTotal]-T0.[PaidToDate]) end as '120',
    T0.[Comments] FROM ORIN T0  INNER JOIN OCTG T1 ON T0.GroupNum = T1.GroupNum INNER JOIN OCRD T2 ON T0.CardCode = T2.CardCode INNER JOIN OCRG T3 ON T2.GroupCode = T3.GroupCode WHERE T0.[DocStatus] ='O' AND  T0.[DocDate] <=[%1] AND  T2.[Cardcode] = 'CCBARTES A/S'
    Thanks!
    Carlo

    Hi Carlo,
    Try below query.
    SELECT max(b.TransType) as [Invoice/Credit Notes], c.CardCode, c.CardName, max(b.RefDate) as DocDate,
    max(b.DueDate) as DocDueDate, max(b.BaseRef) as DocNum,
    CASE WHEN DATEDIFF(DAY, max(b.DueDate), [%1]) < 30 then SUM(a.Debit-a.Credit) end as '0-30',
    CASE WHEN DATEDIFF(DAY, max(b.DueDate), [%1]) BETWEEN 31 and 60 then SUM(a.Debit-a.Credit) end as '31-60',
    CASE WHEN DATEDIFF(DAY, max(b.DueDate), [%1]) BETWEEN 61 and 90 then SUM(a.Debit-a.Credit) end as '61-90',
    CASE WHEN DATEDIFF(DAY, max(b.DueDate), [%1]) BETWEEN 91 and 120 then SUM(a.Debit-a.Credit) end as '91-120',
    CASE WHEN DATEDIFF(DAY, max(b.DueDate), [%1]) > 120 then SUM(a.Debit-a.Credit) end as '120',
    max(x0.Comments) as Remarks
    FROM JDT1 a
    inner join OJDT b on b.TransId = a.TransId
    inner join OCRD c on c.CardCode = a.ShortName
    inner join OCTG d on d.GroupNum = c.GroupNum
    inner join OCRG e on e.GroupCode = c.GroupCode
    left outer join OINV x0 on x0.TransId = b.TransId
    left outer join (select z0.TransId, z0.TransRowId, MAX(z1.ReconDate) as LastReconDate, sum(z0.ReconSum) as ReconSum
      from ITR1 z0
      inner join OITR z1 on z1.ReconNum = z0.ReconNum
      where z1.ReconDate <= [%1] and z1.CancelAbs = 0
      group by z0.TransId, z0.TransRowId
      )f on f.TransId = a.TransId and f.TransRowId = a.Line_ID
    where a.RefDate <= [%1] and c.CardCode = 'CCBARTES A/S'
    group by a.TransId, c.CardCode, c.CardName
    having  CASE when sum(a.Debit - a.Credit) < 0
      then sum(a.Debit - a.Credit) + sum(isnull(f.ReconSum,0))
      else sum(a.Debit - a.Credit) - sum(isnull(f.ReconSum,0)) end <> 0
    Regards,
    Alvin

  • Parameter not accepted in Query Generator

    Dear Experts,
      i had tried customer aging report. it's working fine without parameter (m5.lastname = [0%]) but client needs parameter.  I'm badly stuck with following error
    1). [Microsoft][SQL Server Native Client 10.0][SQL Server]Must specify table to select from. 2). [Microsoft][SQL Server Native Client 10.0][SQL Server]Statement 'Blanket Agreement' (OOAT) (s) could not be prepared.
    My query as below
    SELECT  M2.cardcode 'Customer Code', M2.cardname 'Customer Name', M4.U_salManNm, m2.U_BeatCode, m4. U_salManNm,
    case l.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    WHEN '30' THEN 'J.E'
    else 'Other'
    end 'Type',
    j.BaseRef AS 'Doc.No',
    l.LineMemo AS 'Remarks',
    CONVERT(VARCHAR(10), l.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), l.duedate, 103) 'Due Date',
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 30
    and (datediff(dd,l.refdate,current_timestamp))+1< 61)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "30-61 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 60
    and (datediff(dd,l.refdate,current_timestamp))+1< 91)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "61-90 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 90
    and (datediff(dd,l.refdate,current_timestamp))+1< 121)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "91-120 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 120
    and (datediff(dd,l.refdate,current_timestamp))+1< 181)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "120-180 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 180
    and (datediff(dd,l.refdate,current_timestamp))+1< 221)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "180-220 Days",
    CASE
    when (DATEDIFF(dd,l.refdate,current_timestamp))+1 > 220
    then
    case
    when BalDueCred= 0 then BalDueDeb
    when BalDueDeb= 0 then BalDueCred * - 1
    end
    end "221 + Days"
    FROM JDT1 l
    INNER JOIN OJDT j On j.TransId=l.TransId
    LEFT OUTER JOIN OCRD M2 ON M2.cardcode= l.shortname inner join dbo.[@CQ_RTSM] m4 on m2.U_BeatCode=m4.U_RoutCode inner join ohem m5 on m5.lastname = m4. U_salManNm
    WHERE l.[BalDueDeb]!='0.00' AND  m5.lastName=[%0] and
    M2.cardtype= 'C'
    AND
    l.intrnmatch= '0'
    ORDER BY
    M2.CardCode, l.taxdate

    Hi,
    Try this:
    DECLARE @name AS nvarchar(30)
    /* SELECT FROM [dbo].[OHEM] T0 */
    /* WHERE */
    SET @name = /* T0.lastname */ '[%0]'
    SELECT  M2.cardcode 'Customer Code', M2.cardname 'Customer Name', M4.U_salManNm, m2.U_BeatCode, m4. U_salManNm,
    case l.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    WHEN '30' THEN 'J.E'
    else 'Other'
    end 'Type',
    j.BaseRef AS 'Doc.No',
    l.LineMemo AS 'Remarks',
    CONVERT(VARCHAR(10), l.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), l.duedate, 103) 'Due Date',
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 30
    and (datediff(dd,l.refdate,current_timestamp))+1< 61)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "30-61 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 60
    and (datediff(dd,l.refdate,current_timestamp))+1< 91)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "61-90 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 90
    and (datediff(dd,l.refdate,current_timestamp))+1< 121)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "91-120 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 120
    and (datediff(dd,l.refdate,current_timestamp))+1< 181)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "120-180 Days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 180
    and (datediff(dd,l.refdate,current_timestamp))+1< 221)
    then
    case
    when BalDueCred <> 0 then BalDueCred * - 1
    else BalDueDeb
    end
    end "180-220 Days",
    CASE
    when (DATEDIFF(dd,l.refdate,current_timestamp))+1 > 220
    then
    case
    when BalDueCred= 0 then BalDueDeb
    when BalDueDeb= 0 then BalDueCred * - 1
    end
    end "221 + Days"
    FROM JDT1 l
    INNER JOIN OJDT j On j.TransId=l.TransId
    LEFT OUTER JOIN OCRD M2 ON M2.cardcode= l.shortname inner join dbo.[@CQ_RTSM] m4 on m2.U_BeatCode=m4.U_RoutCode inner join ohem m5 on m5.lastname = m4. U_salManNm
    WHERE l.[BalDueDeb]!='0.00' AND  m5.lastName = @name and
    M2.cardtype= 'C'
    AND
    l.intrnmatch= '0'
    ORDER BY
    M2.CardCode, l.taxdate
    Thanks & Regards,
    Nagarajan

  • Help in Update Query

    Hi, I want to update status_code of table_2. T_ID is the primary key in both table (Table_1 and table_2). The condition is any person's age >70 then status_code should be 'R' and if person's age<70 then status_code should be 'N'. Please help on this
    Update query.
    /*Table_1*/
    T_ID  LASTNAME  FIRSTNAME   DOB
    1001 KAISER      SUJIR    01/01/1942
    1002 SMITH     HUJR       01/01/1948
    1003 JOHN      JANE       02/01/1958
    /*Table_2*/
    T_ID  LASTNAME  FIRSTNAME   STATUS_CODE
    1001 KAISER      SUJIR    R
    1002 SMITH     HUJR       R
    1003 JOHN      JANE        R
    /*Need the Following Result after the Update*/
    T_ID  LASTNAME  FIRSTNAME   STATUS_CODE
    1001 KAISER      SUJIR    R   --The Age is >70 that's why status_code is 'R'
    1002 SMITH     HUJR       N  --The Age is <70
    1003 JOHN      JANE        N  --The Age is <70

    DECLARE @table1 TABLE (T_ID INT, lastName VARCHAR(30), firstName VARCHAR(30), dob DATE)
    INSERT INTO @table1 (T_ID, lastName, firstName, dob) VALUES (1001, 'KAISER', 'SUJIR' ,'01/01/1942'),(1002, 'SMITH', 'HUJR', '01/01/1948'),(1003, 'JOHN', 'JANE', '02/01/1958'),(1004, 'Jack', 'Jackson', '12/03/1944')
    DECLARE @table2 TABLE (T_ID INT, lastName VARCHAR(30), firstName VARCHAR(30), statusCode CHAR(1))
    INSERT INTO @table2 (T_ID, lastName, firstName, statusCode) VALUES (1001, 'KAISER', 'SUJIR', 'R'),(1002, 'SMITH', 'HUJR', 'R'),(1003, 'JOHN', 'JANE', 'R'),(1004, 'Jack', 'Jackson', 'R')
    -- tables set up
    UPDATE @table2
    SET statusCode = CASE WHEN DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP) - CASE WHEN DATEADD(YEAR,DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP),t1.dob) > CURRENT_TIMESTAMP THEN 1 ELSE 0 END >= 70 THEN 'R' ELSE 'N' END
    FROM @table2 t2
    INNER JOIN @table1 t1
    ON t2.T_ID = t1.T_ID
    SELECT *, DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP) - CASE WHEN DATEADD(YEAR,DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP),t1.dob) > CURRENT_TIMESTAMP THEN 1 ELSE 0 END
    FROM @table2 t2
    INNER JOIN @table1 t1
    ON t2.T_ID = t1.T_ID

  • AR Aging Summary

    I am trying to understand how to take my existing query for AR Aging and create a version that is a one line summary. I have the detailed version working correctly down to the penny along side the systems version. Now I need to create the the same thing as the systems when you hit "collapse all" .   I have tried adding sum, and removing the detailed items from the query, but it just gives constant errors.
    Do any of you experts happen to have a query statement already prepared that I can try?
    Thanks!

    The full query that I am using to get the detailed version is:
    SELECT       (SELECT     TOP (1) Projektnummer
                                FROM          P4100_PM.dbo.MPProjektstamm
                                WHERE      (Kostentraeger =
                                                           (SELECT     TOP (1) Project
                                                             FROM          JDT1
                                                             WHERE      (TransId = l.TransId) AND (ISNULL(Project, N'') <> '')))) AS 'Project Number',
                              (SELECT     TOP (1) Projektname
                                FROM          P4100_PM.dbo.MPProjektstamm AS MPProjektstamm_2
                                WHERE      (Kostentraeger =
                                                           (SELECT     TOP (1) Project
                                                             FROM          JDT1 AS JDT1_2
                                                             WHERE      (TransId = l.TransId) AND (ISNULL(Project, N'') <> '')))) AS 'Project Name',
                              (SELECT     Personenname
                                FROM          P4100_PM.dbo.MPPersonenstamm
                                WHERE      (Personalnummer =
                                                           (SELECT     Personalnummer
                                                             FROM          P4100_PM.dbo.MPProjektstammProjektleiter
                                                             WHERE      (ProjektleiterTyp = 1) AND (Projektnummer =
                                                                                    (SELECT     TOP (1) Projektnummer
                                                                                    FROM          P4100_PM.dbo.MPProjektstamm AS MPProjektstamm_1
                                                                                    WHERE      (Kostentraeger =
                                                                                    (SELECT     TOP (1) Project
                                                                                    FROM          JDT1 AS JDT1_1
                                                                                    WHERE      (TransId = l.TransId) AND (ISNULL(Project, N'') <> '')))))))) AS 'Project Mgr',
                              (SELECT     TOP (1) P4100_PM.dbo.MPProjektGruppen.Bezeichnung
                                FROM          P4100_PM.dbo.MPProjektstamm AS MPProjektstamm_3 INNER JOIN
                                                       P4100_PM.dbo.MPProjektGruppen ON P4100_PM.dbo.MPProjektGruppen.GruppenID = MPProjektstamm_3.Umsatzgruppe
                                WHERE      (MPProjektstamm_3.Kostentraeger =
                                                           (SELECT     TOP (1) Project
                                                             FROM          JDT1 AS JDT1_3
                                                             WHERE      (TransId = l.TransId) AND (ISNULL(Project, N'') <> '')))) AS 'Business Group',
                              (SELECT     TOP (1) OcrCode
                                FROM          INV1 AS INV1_1
                                WHERE      (DocEntry = OINV.DocEntry)) AS [Profit Center], OCRD.CardCode AS 'Customer Code', OCRD.CardName AS 'Customer Name',
                          CASE l.transtype WHEN '13' THEN 'AR Invoice' WHEN '14' THEN 'AR Credit Memo' WHEN '15' THEN 'Delivery Note' WHEN '18' THEN 'AP Invoice' WHEN
                           '19' THEN 'AP Credit Memo' WHEN '20' THEN 'Goods Reciept PO' WHEN '202' THEN 'Production Order' WHEN '24' THEN 'Incoming Payment' WHEN '25'
                           THEN 'Deposit' WHEN '30' THEN 'Journal Entry' WHEN '46' THEN 'Outgoing Payments' WHEN '58' THEN 'Stock Taking' WHEN '-3' THEN 'Profilt / Loss'
                           WHEN '60' THEN 'Issue for Production' WHEN '69' THEN 'Landed Costs' ELSE 'Other' END AS 'Doc Type', j.BaseRef AS 'Doc #',
                          CASE OINV.DocStatus WHEN 'C' THEN 'CLOSED' WHEN 'O' THEN 'OPEN' ELSE CASE ORIN.DocStatus WHEN 'C' THEN 'CLOSED' WHEN 'O' THEN 'OPEN'
                           ELSE ' ' END END AS [Doc Status], l.TransId AS [Jrnl Entry #], CONVERT(VARCHAR(10), l.TaxDate, 101) AS 'Doc Date', CONVERT(VARCHAR(10),
                          l.DueDate, 101) AS 'Due Date', OINV.NumAtCard AS 'BPs Ref. No.', CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate)
                          ELSE CASE WHEN (ORIN.DocStatus = 'O') THEN (ORIN.DocTotal - ORIN.PaidToDate) * - 1 ELSE CASE WHEN (l.Transtype = '24')
                          THEN (ORCT.NoDocSum * - 1) ELSE CASE WHEN (l.Transtype = '30') THEN (l.Debit - l.Credit) ELSE '0' END END END END AS 'Open Balance Due',
                          DATEDIFF(dd, l.DueDate, CURRENT_TIMESTAMP) AS 'Days Due', CASE WHEN (DATEDIFF(dd, l.DueDate, CURRENT_TIMESTAMP))
                          <= 0 THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1) ELSE CASE WHEN (OINV.DocStatus = 'O')
                          THEN OINV.DocTotal - OINV.PaidToDate ELSE '0' END END END AS [Current], CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) >= 1 AND
                          (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 31) THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1)
                          ELSE CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate) ELSE '0' END END END AS [1 to 30 days], CASE WHEN ((datediff(dd,
                           l.DueDate, CURRENT_TIMESTAMP)) > 30 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 61) THEN CASE WHEN (l.TransType = '14')
                          THEN (l.Credit * - 1) ELSE CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate) ELSE '0' END END END AS [31 to 60 days],
                          CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 60 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 91)
                          THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1) ELSE CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate)
                          ELSE '0' END END END AS [61 to 90 days], CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 90 AND (datediff(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) < 121) THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1) ELSE CASE WHEN (OINV.DocStatus = 'O')
                          THEN (OINV.DocTotal - OINV.PaidToDate) ELSE '0' END END END AS [91 to 120 days], CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP))
                          > 120 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 181) THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1)
                          ELSE CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate) ELSE '0' END END END AS [121 to 180 days],
                          CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 180 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 366)
                          THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1) ELSE CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate)
                          ELSE '0' END END END AS [181 to 1 Year], CASE WHEN ((datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) > 365 AND (datediff(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) < 545) THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1) ELSE CASE WHEN (OINV.DocStatus = 'O')
                          THEN (OINV.DocTotal - OINV.PaidToDate) ELSE '0' END END END AS [1 Year to 1.5 Years], CASE WHEN ((datediff(dd, l.DueDate,
                          CURRENT_TIMESTAMP)) > 544 AND (datediff(dd, l.DueDate, CURRENT_TIMESTAMP)) < 731) THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1)
                          ELSE CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate) ELSE '0' END END END AS [1.5 Years to 2 Years],
                          CASE WHEN (DATEDIFF(dd, l.DueDate, CURRENT_TIMESTAMP)) > 730 THEN CASE WHEN (l.TransType = '14') THEN (l.Credit * - 1)
                          ELSE CASE WHEN (OINV.DocStatus = 'O') THEN (OINV.DocTotal - OINV.PaidToDate) ELSE '0' END END END AS [2 Years and Greater], (SELECT     SUM(P.LineTotal) AS Expr1
                           FROM          INV1 AS P INNER JOIN
                                                  OINV AS PP ON P.DocEntry = PP.DocEntry
                           WHERE      (P.AcctCode = '41101-001') AND (PP.DocNum = j.BaseRef)) AS Retention,
                          CASE l.transtype WHEN '13' THEN
                              (SELECT     Comments
                                FROM          OINV
                                WHERE      OINV.Transid = j.Transid) ELSE '-' END AS [Invoice Remarks]
    FROM         JDT1 AS l INNER JOIN
                          OJDT AS j ON j.TransId = l.TransId INNER JOIN
                          OCRD ON l.ShortName = OCRD.CardCode LEFT OUTER JOIN
                          ORCT ON l.TransId = ORCT.TransId LEFT OUTER JOIN
                          ORIN ON l.TransId = ORIN.TransId LEFT OUTER JOIN
                          OINV ON l.TransId = OINV.TransId
    WHERE     (OCRD.CardType = 'c') AND (l.BalScDeb <> l.BalScCred) AND (OCRD.Balance <> 0)
    ORDER BY 'Project Number', 'Project Mgr', 'Customer Code', 'Customer Name', l.TaxDate
    I am also pulling in items from Maringo's Project management add on. you can see those as the P4100_PM.dbo lines.
    THANKS

  • Receivables Ageing Summary 90+ Days Variable in 8.8

    Hi Experts
    In 2007A there was a variable for the Customer Receivables Ageing Summary PLD which totalled all outstanding values from 90+.  The variable was 115.  Does anyone know what this variable is in 8.8 please?  I haved checked the file which is on the SAP Portal which lists all the variables however it doesn't list the variables for the Aging reports.
    Many thanks,
    Caroline

    Hi Caroline,
    Not sure if this will help but we are using this here:
    select T0.shortname,T2.cardcode 'Customer Code',T2.cardname 'Name', sysdeb 'Debit Amount',syscred 'Credit Amount',
    case T0.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    T1.BaseRef'Trans #',
    case T0.transtype
    when '13' then
    (Select Comments from OINV where OINV.Transid=T1.Transid)
    else '-'
    end 'Inv.Rem.',
    (Select SeriesName From NNM1 Where Series=T1.DocSeries and ObjectCode=T0.TransType)'Series',
    T0.Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), T0.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), T0.duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), T0.taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "0-30 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30
    and (datediff(dd,T0.refdate,current_timestamp))+1< 61)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60
    and (datediff(dd,T0.refdate,current_timestamp))+1< 91)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "60 to 90 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90
    and (datediff(dd,T0.refdate,current_timestamp))+1< 121)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "91 to 120 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 120
    and (datediff(dd,T0.refdate,current_timestamp))+1< 151)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "121 to 150 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 150
    and (datediff(dd,T0.refdate,current_timestamp))+1< 181)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "151 to 180 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 180
    and (datediff(dd,T0.refdate,current_timestamp))+1< 221)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "181 to 220 days",
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 220
    then
    case
    when syscred= 0 then sysdeb
    when sysdeb= 0 then syscred * - 1
    end
    end "220 + days"
    from JDT1 T0
    Inner Join OJDT T1 On T1.TransId=T0.TransId
    left outer join
    OCRD T2 ON T2.cardcode =T0.shortname where
    T2.cardtype = 'c' and T0.intrnmatch = '0'
    and (T0.BalDueCred = '0' OR T0.BalDueDeb = '0' )
    ORDER BY T2.CARDCODE, T0.taxdate
    Kind regards
    Sean Martin
    Arrow Industrial
    Edited by: Sean Martin on Feb 4, 2011 10:31 AM

  • Error In Aged Debtors Query

    Hi there
    I've tring to produce an aged debtor query and am getting the following error am producing this report in qlikview
    SQL error: The multi-part identifier "T0.ShortName" could not be bound
    Please could some one look at my query and tell me where am going wrong i beleve it's something to do with my inner join but am not sure as am fairly new to this
    Any help would be most appreciated as am at a total dead end on this one
    <p></p>
    SELECT <br>
    T0.ShortName 'Account Code',<br>
    T0.intrnmatch 'Internal Reconciliation No',<br>
    T0.BALDUEDEB, <br>
    T0.BALDUECRED,<br>
    T0.sysdeb 'System Debit Amount',<br>
    T0.syscred 'System Credit Amount',<br>
    (T0.sysdeb - T0.syscred) AS 'System Balance Due', <br>
    T0.debit 'Local Debit Amount',<br>
    T0.credit 'Local Credit Amount',<br>
    (T0.debit - T0.credit) AS 'Local Balance Due',<br>
    T0.fcdebit 'FC Debit Amount',<br>
    T0.fccredit 'FC Credit Amount',<br>
    (T0.fcdebit - T0.fccredit) AS 'FC Balance Due',<br>
    case T0.fccurrency<br>
         when 'EUR' then T0.fcdebit - T0.fccredit<br>
         when 'USD' then T0.sysdeb - T0.syscred<br>
         else T0.debit - T0.credit<br>
    end 'Balance Due',<br>
    case T0.transtype<br>
         when '13' then 'INV'<br>
         when '14' then 'AR CN'<br>
         when '24' then 'INCOMING'<br>
         else 'Other'<br>
    end 'Type',<br>
    T0.Ref1,<br>
    T0.fccurrency 'BP Currency',<br>
    CONVERT(VARCHAR(10), T0.refdate, 103) 'Posting Date',<br>
    CONVERT(VARCHAR(10), T0.duedate, 103) 'Due Date',<br>
    CONVERT(VARCHAR(10), T0.taxdate, 103) 'Doc Date' ,<br>
    T1.WhsCode 'Warehouse',<br>
    T2.cardcode 'Bp Code',<br>
    T2.cardname 'Name',<br>
    T2.SlpCode 'Slp Code',<br>
    T2.GroupCode 'Group Code',<br>
    T2.CreditLine 'Credit Limit',<br>
    T2.DebtLine 'Debt Limit',<br>
    T3.GroupName 'Customer Name',<br>
    T3.GroupType 'Group Type',<br>
    T4.ItmsGrpCod 'Item Group Code',<br>
    T5.ItmsGrpNam 'Item Group Name',<br>
    T6.SlpName 'Sales Employee',<br>
    //Calculate 0-30 Days
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31
              then
              case
                   when T0.syscred <> 0 then -T0.syscred
                        else T0.sysdeb
              end
    end "System 0-30 days",
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31          then
              case
                   when T0.credit <> 0 then -T0.credit
                        else T0.debit
              end
    end "LC 0-30 days",
    CASE
    when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31
              then
              case
                   when T0.fccredit <> 0 then -T0.fccredit
                        else T0.fcdebit
              end
    end "FC 0-30 days",
    // Calculate 31-60 Days
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30
    and (datediff(dd,T0.refdate,current_timestamp))+1< 61)
              then
              case
                   when T0.syscred <> 0 then -T0.syscred
                        else T0.sysdeb
              end
    end "System 31-60 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30
    and (datediff(dd,T0.refdate,current_timestamp))+1< 61)
              then
              case
                   when T0.credit <> 0 then -T0.credit
                        else T0.debit
              end
    end "LC 31-60 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30
    and (datediff(dd,T0.refdate,current_timestamp))+1< 61)
              then
              case
                   when T0.fccredit <> 0 then -T0.fccredit
                        else T0.fcdebit
              end
    end "FC 31-60 days",
    // Calculate 61-90 Days
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60
    and (datediff(dd,T0.refdate,current_timestamp))+1< 91)
              then
              case
                   when T0.syscred <> 0 then -T0.syscred
                        else T0.sysdeb
              end
    end "System 61-90 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60
    and (datediff(dd,T0.refdate,current_timestamp))+1< 91)
              then
              case
                   when T0.credit <> 0 then -T0.credit
                        else T0.debit
              end
    end "LC 61-90 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60
    and (datediff(dd,T0.refdate,current_timestamp))+1< 91)
              then
              case
                   when T0.fccredit <> 0 then -T0.fccredit
                        else T0.fcdebit
              end
    end "FC 61-90 days",
    // Calculate 91-120 Days
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90
    and (datediff(dd,T0.refdate,current_timestamp))+1< 121)
              then
              case
                   when T0.syscred <> 0 then -T0.syscred
                        else T0.sysdeb
              end
    end "System 91-120 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90
    and (datediff(dd,T0.refdate,current_timestamp))+1< 121)
              then
              case
                   when T0.credit <> 0 then -T0.credit
                        else T0.debit
              end
    end "LC 91-120 days",
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90
    and (datediff(dd,T0.refdate,current_timestamp))+1< 121)
              then
              case
                   when T0.fccredit <> 0 then -T0.fccredit
                        else T0.fcdebit
              end
    end "FC 91-120 days",
    // Calculate 120+ Days
    CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 120
              then
              case
                   when T0.syscred= 0 then T0.sysdeb
                   when T0.sysdeb= 0 then -T0.syscred
              end
    end "System 120+ days",
    CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 120
              then
              case
                   when T0.credit= 0 then T0.debit
                   when T0.debit= 0 then -T0.credit
              end
    end "LC 120+ days",
    CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 120
              then
              case
                   when T0.fccredit= 0 then T0.fcdebit
                   when T0.fcdebit= 0 then -T0.fccredit
              end
    end "FC 120+ days"<br>
    FROM JDT1 T0, INV1 T1<br>
    INNER JOIN OCRD T2 ON T1.BaseCard = T2.CardCode AND T0.ShortName = T2.CardCode AND T2.CardType = 'C' <br>
    INNER JOIN OCRG T3 ON T2.GroupCode = T3.GroupCode <br>
    INNER JOIN OITM T4 ON T1.ItemCode = T4.ItemCode <br>
    INNER JOIN OITB T5 ON T4.ItmsGrpCod = T5.ItmsGrpCod <br>
    INNER JOIN OSLP T6 ON T1.SlpCode = T6.SlpCode <br>
    WHERE T0.intrnmatch = '0' AND T0.BALDUEDEB != T0.BALDUECRED <br>
    ORDER BY T2.CardCode;<br>
    Edited by: Mcphee78 on Oct 15, 2010 2:38 PM

    HI,
    Try below query:
    SELECT
    T0.ShortName 'Account Code',
    T0.intrnmatch 'Internal Reconciliation No',
    T0.BALDUEDEB,
    T0.BALDUECRED,
    T0.sysdeb 'System Debit Amount',
    T0.syscred 'System Credit Amount',
    (T0.sysdeb - T0.syscred) AS 'System Balance Due',
    T0.debit 'Local Debit Amount',
    T0.credit 'Local Credit Amount',
    (T0.debit - T0.credit) AS 'Local Balance Due',
    T0.fcdebit 'FC Debit Amount',
    T0.fccredit 'FC Credit Amount',
    (T0.fcdebit - T0.fccredit) AS 'FC Balance Due',
    case T0.fccurrency
    when 'EUR' then T0.fcdebit - T0.fccredit
    when 'USD' then T0.sysdeb - T0.syscred
    else T0.debit - T0.credit
    end 'Balance Due',
    case T0.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    T0.Ref1,
    T0.fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), T0.refdate, 103) 'Posting Date',
    CONVERT(VARCHAR(10), T0.duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), T0.taxdate, 103) 'Doc Date' ,
    T1.WhsCode 'Warehouse',
    T2.cardcode 'Bp Code',
    T2.cardname 'Name',
    T2.SlpCode 'Slp Code',
    T2.GroupCode 'Group Code',
    T2.CreditLine 'Credit Limit',
    T2.DebtLine 'Debt Limit',
    T3.GroupName 'Customer Name',
    T3.GroupType 'Group Type',
    T4.ItmsGrpCod 'Item Group Code',
    T5.ItmsGrpNam 'Item Group Name',
    T6.SlpName 'Sales Employee',
    --Calculate 0-30 Days
    CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31 then case when T0.syscred <> 0 then -T0.syscred else T0.sysdeb end end "System 0-30 days", CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31 then case when T0.credit <> 0 then -T0.credit else T0.debit end end "LC 0-30 days", CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 < 31 then case when T0.fccredit <> 0 then -T0.fccredit else T0.fcdebit end end "FC 0-30 days",
    -- Calculate 31-60 Days
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30 and (datediff(dd,T0.refdate,current_timestamp))+1< 61) then case when T0.syscred <> 0 then -T0.syscred else T0.sysdeb end end "System 31-60 days", case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30 and (datediff(dd,T0.refdate,current_timestamp))+1< 61) then case when T0.credit <> 0 then -T0.credit else T0.debit end end "LC 31-60 days", case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 30 and (datediff(dd,T0.refdate,current_timestamp))+1< 61) then case when T0.fccredit <> 0 then -T0.fccredit else T0.fcdebit end end "FC 31-60 days",
    --Calculate 61-90 Days
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60 and (datediff(dd,T0.refdate,current_timestamp))+1< 91) then case when T0.syscred <> 0 then -T0.syscred else T0.sysdeb end end "System 61-90 days", case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60 and (datediff(dd,T0.refdate,current_timestamp))+1< 91) then case when T0.credit <> 0 then -T0.credit else T0.debit end end "LC 61-90 days", case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 60 and (datediff(dd,T0.refdate,current_timestamp))+1< 91) then case when T0.fccredit <> 0 then -T0.fccredit else T0.fcdebit end end "FC 61-90 days",
    -- Calculate 91-120 Days
    case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90 and (datediff(dd,T0.refdate,current_timestamp))+1< 121) then case when T0.syscred <> 0 then -T0.syscred else T0.sysdeb end end "System 91-120 days", case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90 and (datediff(dd,T0.refdate,current_timestamp))+1< 121) then case when T0.credit <> 0 then -T0.credit else T0.debit end end "LC 91-120 days", case when ((datediff(dd,T0.refdate,current_timestamp))+1 > 90 and (datediff(dd,T0.refdate,current_timestamp))+1< 121) then case when T0.fccredit <> 0 then -T0.fccredit else T0.fcdebit end end "FC 91-120 days",
    -- Calculate 120+ Days
      CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 120 then case when T0.syscred= 0 then T0.sysdeb when T0.sysdeb= 0 then -T0.syscred end end "System 120+ days", CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 120 then case when T0.credit= 0 then T0.debit when T0.debit= 0 then -T0.credit end end "LC 120+ days", CASE when (DATEDIFF(dd,T0.refdate,current_timestamp))+1 > 120 then case when T0.fccredit= 0 then T0.fcdebit when T0.fcdebit= 0 then -T0.fccredit end end "FC 120+ days"
    FROM JDT1 T0, INV1 T1
    INNER JOIN OCRD T2 ON T1.BaseCard = T2.CardCode AND T2.CardType = 'C'
    INNER JOIN OCRG T3 ON T2.GroupCode = T3.GroupCode
    INNER JOIN OITM T4 ON T1.ItemCode = T4.ItemCode
    INNER JOIN OITB T5 ON T4.ItmsGrpCod = T5.ItmsGrpCod
    INNER JOIN OSLP T6 ON T1.SlpCode = T6.SlpCode
    WHERE T0.intrnmatch = '0' AND T0.BALDUEDEB != T0.BALDUECRED and (T0.ShortName=T2.CardCode )
    ORDER BY T2.CardCode
    Thanks,
    Neetu

  • Recursive CTE to get first business day excluding public holidays

    I wanted to write a recursive CTE to calculate the first business day excluding the public holidays for a given year. I have a table with the public holiday for that same year

    I like the functions I built to get this done:
    create function NthDayOfMonth (@year int, @month smallint, @weekday varchar(15), @nth smallint)
    returns datetime
    as
    begin
    declare @the_date datetime, @c_date datetime, @cth smallint
    set @cth = 0
    set @c_date = convert(varchar,@year)+'-'+convert(varchar,@month)+'-01'
    while month(@c_date) = @month
    begin
    if datename(weekday,@c_date) = @weekday set @cth = @cth + 1
    if @cth = @nth and datename(weekday,@c_date) = @weekday set @the_date = @c_date
    set @c_date = dateadd(day,1,@c_date)
    end
    return @the_date
    end
    GO
    create function Holidays(@year int)
    returns @table table
    date date,
    type varchar(10),
    name varchar(25)
    as
    begin
    insert into @table
    select convert(datetime,convert(varchar,@year)+'-01-01') as date,'Holiday' as type ,'New Years Day' as name UNION ALL
    select dbo.NthDayOfMonth(@year,2, 'Monday',3),'Holiday','Family Day' UNION ALL
    select dateadd(d,0-case when datepart(weekday,convert(varchar,@year)+'-05-25') in (1,2) then 5+datepart(weekday,convert(varchar,@year)+'-05-25') else datepart(weekday,convert(varchar,@year)+'-05-25')-1 end, convert(varchar,@year)+'-05-25') ,'Holiday','Victoria Day' UNION ALL
    select convert(varchar,@year)+'-07-01' ,'Holiday','Canada Day' UNION ALL
    select dbo.NthDayOfMonth(@year,8, 'Monday',1),'Holiday','Civic Holiday' UNION ALL
    select dbo.NthDayOfMonth(@year,9, 'Monday',1),'Holiday','Labour Day' UNION ALL
    select dbo.NthDayofMonth(@year,10,'Monday',2),'Holiday','Thanksgiving' UNION ALL
    select convert(varchar,@year)+'-11-11' ,'Holiday','Rememberance Day'UNION ALL
    select convert(varchar,@year)+'-12-25' ,'Holiday','Christmas Day' UNION ALL
    select convert(varchar,@year)+'-12-26' ,'Holiday','Boxing Day' UNION ALL
    SELECT CONVERT(DATE,CONVERT(VARCHAR,@year) + '-0'+CONVERT(VARCHAR, FLOOR((((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + 90) / 25))+'-'+CONVERT(VARCHAR,CONVERT(INT,(((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + (FLOOR((((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + 90) / 25)) + 19) % 32,0))),'Holiday','Easter Sunday' UNION ALL
    SELECT DATEADD(DAY,-2,CONVERT(DATE,CONVERT(VARCHAR,@year) + '-0'+CONVERT(VARCHAR, FLOOR((((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + 90) / 25))+'-'+CONVERT(VARCHAR,CONVERT(INT,(((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + (FLOOR((((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + 90) / 25)) + 19) % 32,0)))),'Holiday','Good Friday' UNION ALL
    SELECT DATEADD(DAY,1,CONVERT(DATE,CONVERT(VARCHAR,@year) + '-0'+CONVERT(VARCHAR, FLOOR((((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + 90) / 25))+'-'+CONVERT(VARCHAR,CONVERT(INT,(((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + (FLOOR((((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) - (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) + ((((2 * FLOOR((@year / 100.0)) % 4) + (2*((@year % 100) / 4))) - ((@year % 100) % 4) - ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30) + (FLOOR((@year % 19.0 + (11 * ((( (19 * (@year % 19.0)) + FLOOR(@year / 100.0)) - FLOOR((@year / 100.0) / 4) - FLOOR((8 * (@year / 100.0) + 13) / 25.0) + 15) % 30))) / 319)) +32) % 7) + 90) / 25)) + 19) % 32,0)))),'Holiday','Easter Monday'
    update @table
    set date =
    case when MONTH(date) = 12 AND name != 'Boxing Day' and datepart(weekday,date) = 7 then dateadd(day,2,date)
    when MONTH(date) = 12 AND name != 'Boxing Day' and datepart(weekday,date) = 1 then dateadd(day,1,date)
    when MONTH(date) = 12 AND name = 'Boxing Day' and datepart(weekday,date) = 7 then dateadd(day,2,date)
    when MONTH(date) = 12 AND name = 'Boxing Day' and datepart(weekday,date) = 1 then dateadd(day,2,date)
    when MONTH(date) = 12 AND name = 'Boxing Day' and datepart(weekday,date) = 2 then dateadd(day,1,date)
    else date
    end
    return
    end
    GO
    create function Dates(@date datetime)
    returns @table table
    now datetime,
    today datetime,
    Month_start datetime,
    Month_end datetime,
    Prev_Month_Start datetime,
    Prev_Month_End datetime,
    Week_Start datetime,
    Week_End datetime,
    Prev_Week_Start datetime,
    Prev_Week_End datetime,
    Quarter_Start datetime,
    Quarter_End datetime,
    Prev_Quarter_Start datetime,
    Prev_Quarter_End datetime,
    Year_Start datetime,
    Year_End datetime,
    Prev_Year_Start datetime,
    Prev_Year_End datetime,
    Month_End_TS datetime,
    Prev_Month_End_TS datetime,
    Week_End_TS datetime,
    Prev_Week_End_TS datetime,
    Quarter_End_TS datetime,
    Prev_Quarter_End_TS datetime,
    Year_End_TS datetime,
    Prev_Year_End_TS datetime,
    Year smallint,
    Month smallint,
    Day smallint,
    Month_Name varchar(15),
    Day_Name varchar(15),
    WD SMALLINT,
    Week INT,
    isHoliday bit
    as
    begin
    if @date IS NULL set @date = getdate()
    insert into @table
    select
    @date as now,
    convert(datetime,convert(varchar,@date,101)) as today,
    dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101))) as Month_Start,
    dateadd(day,-1,dateadd(month,1,dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101))))) as Month_end,
    dateadd(month,-1,dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101)))) as Prev_Month_start,
    dateadd(day,-1-day(@date)+1,convert(datetime,convert(varchar,@date,101))) as Prev_Month_End,
    dateadd(day,1-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Week_Start,
    dateadd(day,7-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Week_End,
    dateadd(day,-6-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Prev_Week_Start,
    dateadd(day,0-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Prev_Week_End,
    convert(datetime,convert(varchar,year(@date)) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,@date)-1)*3)+1),2)+'-01') as quarter_start,
    dateadd(day,-1,dateadd(quarter,1,convert(datetime,convert(varchar,year(@date)) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,@date)-1)*3)+1),2)+'-01'))) as quarter_end,
    convert(datetime,convert(varchar,year(dateadd(quarter,-1,@date))) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,dateadd(quarter,-1,@date))-1)*3)+1),2)+'-01') as prev_quarter_start,
    dateadd(day,-1,dateadd(quarter,1,convert(datetime,convert(varchar,year(dateadd(quarter,-1,@date))) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,dateadd(quarter,-1,@date))-1)*3)+1),2)+'-01'))) as prev_quarter_end,
    dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101))) as Year_Start,
    dateadd(year,1,dateadd(day,0-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101)))) as Year_End,
    dateadd(year,-1,dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101)))) as Prev_Year_Start,
    dateadd(year,-1,dateadd(year,1,dateadd(day,0-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101))))) as Prev_Year_End,
    dateadd(ms,-3,dateadd(day,0,dateadd(month,1,dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101)))))) as Month_End_Ts,
    dateadd(ms,-3,dateadd(day,-1-day(@date)+2,convert(datetime,convert(varchar,@date,101)))) as Prev_Month_End_TS,
    dateadd(ms,-3,dateadd(day,8-datepart(dw,@date),convert(datetime,convert(varchar,@date,101)))) as Week_End_TS,
    dateadd(ms,-3,dateadd(day,1-datepart(dw,@date),convert(datetime,convert(varchar,@date,101)))) as Prev_Week_End_TS,
    dateadd(ms,-3,dateadd(day,0,dateadd(quarter,1,convert(datetime,convert(varchar,year(@date)) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,@date)-1)*3)+1),2)+'-01')))) as quarter_end_TS,
    dateadd(ms,-3,dateadd(day,0,dateadd(quarter,1,convert(datetime,convert(varchar,year(dateadd(quarter,-1,@date))) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,dateadd(quarter,-1,@date))-1)*3)+1),2)+'-01')))) as prev_quarter_end_TS,
    dateadd(ms,-3,dateadd(year,1,dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101))))) as Year_End_TS,
    dateadd(ms,-3,dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101)))) as Prev_Year_End_TS,
    Year(@date) as Year,
    Month(@date) as Month,
    Day(@Date) as Day,
    datename(month,@Date) as Month_Name,
    datename(WEEKDAY,@date) as Day_Name,
    datepart(weekday,@date) as WD,
    DATEPART(WEEK,@date) AS Week,
    COALESCE((SELECT 1
    FROM dbo.Holidays(YEAR(@date)) h
    WHERE h.date = @date),0) AS isHoliday
    return
    end
    go
    The holidays function is set up for Saskatchewan right now, but its a small matter to adjust it to your region.
    You can then do this:
    DECLARE @calendar TABLE (date DATE)
    WHILE (SELECT COUNT(*) FROM @calendar) < 365
    BEGIN
    INSERT INTO @calendar (date)
    VALUES (DATEADD(day,1,(SELECT COALESCE(MAX(date),CURRENT_TIMESTAMP) FROM @calendar)))
    END
    SELECT MONTH(date) AS month, MIN(date) AS fbd
    FROM @calendar c
    CROSS APPLY dbo.Dates(c.date)
    WHERE DATEPART(DAY,c.date) NOT IN (1,7) AND isHoliday = 0
    GROUP BY MONTH(date)

Maybe you are looking for

  • Can no longer drag MP3 from PC to iTunes on Mac

    I've previously purchased/downloaded hundreds of songs in MP3 format on my PC and have not had a problem dragging them into iTunes over the network. Yesterday I upgraded Firefox to 3.0.1 on both computers and the songs I subsequently downloaded will

  • Address Book Sync Problems - 8530 and Outlook 2007

    This has been a nagging problem for me for quite some time.  Here's my current status: Curve 8530 on Verizon Wireless Access to Corporate resources and email via BES I also access Gmail from the device Right now I am not synching over the air - that

  • Officejet k7100 - Wont print on darker coloured paper

    Hi all I'm hoping for some help. I like playing around and I want to print on some lazer blue paper in greyscale. However, every time I try the printer appears to ignore the fact I have paper in the tray and seems to give an error of 'No paper'. I ha

  • Linking to SQL Server using Transparent Gateways

    I want to use the Transparent Gateways to link to a SQL Server DB. I downloaded Oracle Enterprise Server from OTN. As far as I can tell, the Transparent Gateways are supposed to be bundled with Oracle Enterprise Server, but I can't find them from the

  • How to configure workflow notification mailer for iPad

    EBS R12.1.3 Sun Solaris 11 DB 11g First i apologize for users here becasue i have to repost this. May be i did not ask proper question last time Currently my users got the internet expense or requsition approval in  an email with an attachment and wh