SQl Query to Calculate No of Days from LastDate and PreviousDate

Hi All,
Below is a sample table which holds the rent updates done for properties at any point of time.
I like the query to show the out put as
Prop_Code, PreviousRent, PreviousRentUpdateDate, LastRent, LastRentUpdateDate  NoofDays
1008             206.38           2014-06-16                    
    209.04     2014-12-22               189
DECLARE @table TABLE
 ( Prop_Code INT
 ,Current_Rent INT
 ,Revised_Rent INT
 ,Rent_Review_Date varchar(10)
 ,Rent_Review_Time DATEtime)
INSERT INTO @table (PROP_CODE,Current_Rent,Revised_Rent,Rent_Review_Date,Rent_Review_Time) VALUES
(2977,372,339.15,'2013-07-08','7:44')
,(2977,372,339.15,'2013-07-03','11:01')
,(2977,372,372,'2014-06-30','9:07')
,(2977,372,372,'2014-07-07','11:06')
,(2981,372,372,'2014-07-07','11:06')
,(2981,372,340.15,'2013-07-08','7:23')
,(2981,372,314.15,'2013-07-08','7:44')
,(2981,372,340.15,'2013-07-29','7:16')
,(3089,205.63,400,'2014-10-27','8:38')
,(3089,205.63,205.63,'2014-02-03','8:29')
,(3089,205.63,127.64,'2014-01-20','0:52')
,(3089,205.63,123.02,'2013-08-12','8:28')
,(3089,205.63,205.63,'2014-12-15','8:46')
,(3109,252.62,198,'2014-01-20','0:52')
,(3109,252.62,252.62,'2014-04-07','8:30')
,(3109,252.62,198,'2013-08-12','8:28')
,(3117,284.96,336,'2014-04-21','1:03')
,(3125,267.53,267.53,'2014-02-03','8:29')
,1008,       181.32, '2013-03-19, '04:41')
,(1008 ,      186.15, '2013-03-19, '04:41')
,(1008 ,      187.62, '2013-03-19, '04:41')
,(1008,       191.07, '2013-03-19, '04:41')
,(1008,      202.33, '2013-08-12', '08:28')
,(1008,       202.53, '2013-11-25', '08:33')
,(1008,       206.38, '2014-06-16', '09:38')
,(1008,       209.04, '2014-12-22', '07:55')
Select * from @table
Regards,
Jag

INSERT statement had error and incorrect data. I changed it
Rent column had INT data type and I changed it to Money.
DECLARE @table TABLE
( Prop_Code INT
,Current_Rent Money
,Revised_Rent Money
,Rent_Review_Date varchar(10)
,Rent_Review_Time DATEtime)
INSERT INTO @table (PROP_CODE,Current_Rent,Revised_Rent,Rent_Review_Date,Rent_Review_Time) VALUES
(2977,372,339.15,'2013-07-08','7:44')
,(2977,372,339.15,'2013-07-03','11:01')
,(2977,372,372,'2014-06-30','9:07')
,(2977,372,372,'2014-07-07','11:06')
,(2981,372,372,'2014-07-07','11:06')
,(2981,372,340.15,'2013-07-08','7:23')
,(2981,372,314.15,'2013-07-08','7:44')
,(2981,372,340.15,'2013-07-29','7:16')
,(3089,205.63,400,'2014-10-27','8:38')
,(3089,205.63,205.63,'2014-02-03','8:29')
,(3089,205.63,127.64,'2014-01-20','0:52')
,(3089,205.63,123.02,'2013-08-12','8:28')
,(3089,205.63,205.63,'2014-12-15','8:46')
,(3109,252.62,198,'2014-01-20','0:52')
,(3109,252.62,252.62,'2014-04-07','8:30')
,(3109,252.62,198,'2013-08-12','8:28')
,(3117,284.96,336,'2014-04-21','1:03')
,(3125,267.53,267.53,'2014-02-03','8:29')
,(1008, NULL ,181.32, '2013-03-19', '04:41')
,(1008 , NULL , 186.15, '2013-03-19', '04:41')
,(1008 ,NULL , 187.62, '2013-03-19', '04:41')
,(1008, NULL , 191.07, '2013-03-19', '04:41')
,(1008, NULL , 202.33, '2013-08-12', '08:28')
,(1008, NULL , 202.53, '2013-11-25', '08:33')
,(1008, NULL , 206.38, '2014-06-16', '09:38')
,(1008, NULL , 209.04, '2014-12-22', '07:55')
WITH TempCTE
AS (
SELECT *
,ROW_NUMBER() OVER (
PARTITION BY Prop_Code ORDER BY Rent_Review_Date DESC
) RowNum
FROM @table
SELECT a.Prop_Code
,a.Revised_Rent
,a.Rent_Review_Date
,b.Revised_Rent
,b.Rent_Review_Date
,DATEDIFF(Day, a.Rent_Review_Date, b.Rent_Review_Date)
FROM TempCTE a
INNER JOIN TempCTE b ON a.Prop_Code = b.Prop_Code
AND a.RowNum = b.RowNum + 1
WHERE b.RowNum = 1
-Vaibhav Chaudhari

Similar Messages

  • Put SQL query in a function/ call function from region

    How can I write a SQL query (like SELECT EMPNO, ENAME, JOB FROM EMP) as PL/SQL function, and then call this function from the PL/SQL Function Returning SQL Statement region?
    Thanks, Tom

    thanks jverd for your quick reply.
    I know passing in a reference to an object will do the job if I want to change the value several parameters in one function call.
    But I want to ask, is there any other ways?
    the following code works.....
    public class TestParameter {
         public static void main(String[] args) {
              Test2 t2 = new Test2();
              invokeChange(t2);
              System.out.println("x = " + t2.x + "\t y = " + t2.y);
         static void invokeChange(Test2 t2) {
              t2.x = 10;
              t2.y = 15;          
    class Test2 {     
         int x;
         int y;     
    }

  • Is there a way I can have my form calculate a total time from beginning and ending time?

    Is there a way I can have my form calculate a total time from beginning and ending time?

    Sorry, but Formscentral doesn't support either a timer function or any kind of calculation. You might be able to do this if created your form in PDF. For help with PDF form creation in Acrobat I suggest you repost your question to the Acrobat Forum.
    Andrew

  • SQL Query to calculate on-time dispatch with a calendar table

    Hi Guys,
    I have a query (view) to calculate orders' fulfillment leadtimes.
    The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name
    isBusinessDay but I don't know how to best use this table to calculate the On-Time metric. I have been looking everywhere but so far I have been unable to solve my problem.
    Please find below the current calculation for the On-Time Column:
    SELECT
    Week#
    , ClntGroup
    , CORD_DocumentCode
    , DESP_DocumentCode
    , Cord_Lines --#lines ordered
    , CORD_Qty --total units orderd
    , DESP_Lines --#lines dispatched
    , DESP_Qty --total units dispatched
    , Status
    , d_status
    , OpenDate --order open date
    , DateDue
    , DESP_PostedDate --order dispatched date
    , DocType
    , [Lead times1]
    , [Lead times2]
    , InFxO
    , OnTime
    , InFxO + OnTime AS InFullAndOneTime
    , SLADue
    FROM (
    SELECT
    DATEPART(WEEK, d.DateOpn) AS Week#
    , Clients.CustCateg
    , Clients.ClntGroup
    , d.DocumentCode AS CORD_DocumentCode
    , CDSPDocs.DocumentCode AS DESP_DocumentCode
    , COUNT(CORDLines.Qnty) AS Cord_Lines
    , SUM(CORDLines.Qnty) AS CORD_Qty
    , COUNT(CDSPLines.Qnty) AS DESP_Lines
    , SUM(CDSPLines.Qnty) AS DESP_Qty
    , CDSPLines.Status
    , d.Status AS d_status
    , d.OpenDate
    , d.DateDue
    , CDSPDocs.PostDate AS DESP_PostedDate
    , d.DocType
    , DATEDIFF(DAY, d.OpenDate, d.DateDue) AS [Lead times1]
    , DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) AS [Lead times2]
    , CASE WHEN SUM(CORDLines.Qnty) = SUM(CDSPLines.Qnty) THEN 1 ELSE 0 END AS InFxO --in-full
    --On-Time by order according to Despatch SLAs
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales', 'Mail Order')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2 ) <= 2)
    THEN 1
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - USA')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2) <= 14)
    THEN 1
    WHEN Clients.ClntGroup = 'Export Market' OR Clients.CustCateg = 'UK Transfer'
    AND d.DateDue >= CDSPDocs.PostDate
    THEN 1
    ELSE 0
    END AS OnTime
    --SLA Due (as a control)
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales','Mail Order') AND CDSPDocs.PostDate is Null
    THEN DATEADD(DAY, 2 , d.OpenDate)
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - UK', 'Export Market - USA') OR (Clients.CustCateg = 'UK Transfer')
    AND CDSPDocs.PostDate IS NULL
    THEN DATEADD (DAY, 14 , d.OpenDate)
    ELSE CDSPDocs.PostDate
    END AS SLADue
    FROM dbo.Documents AS d
    INNER JOIN dbo.Clients
    ON d.ObjectID = dbo.Clients.ClntID
    AND Clients.ClientName NOT in ('Samples - Free / Give-aways')
    LEFT OUTER JOIN dbo.DocumentsLines AS CORDLines
    ON d.DocID = CORDLines.DocID
    AND CORDLines.TrnType = 'L'
    LEFT OUTER JOIN dbo.DocumentsLines AS CDSPLines
    ON CORDLines.TranID = CDSPLines.SourceID
    AND CDSPLines.TrnType = 'L'
    AND (CDSPLines.Status = 'Posted' OR CDSPLines.Status = 'Closed')
    LEFT OUTER JOIN dbo.Documents AS CDSPDocs
    ON CDSPLines.DocID = CDSPDocs.DocID
    LEFT OUTER JOIN DimDate
    ON dimdate.[Date] = d.OpenDate
    WHERE
    d.DocType IN ('CASW', 'CORD', 'MORD')
    AND CORDLines.LneType NOT IN ('Fght', 'MANF', 'Stor','PACK', 'EXPS')
    AND CORDLines.LneType IS NOT NULL
    AND d.DateDue <= CONVERT(date, GETDATE(), 101)
    GROUP BY
    d.DateOpn
    ,d.DocumentCode
    ,Clients.CustCateg
    ,CDSPDocs.DocumentCode
    ,d.Status
    ,d.DocType
    ,d.OpenDate
    ,d.DateReq
    ,CDSPDocs.PostDate
    ,CDSPLines.Status
    ,Clients.ClntGroup
    ,d.DocumentName
    ,d.DateDue
    ,d.DateOpn
    ) AS derived_table
    Please find below the DimDate table
    FullDateNZ HolidayNZ IsHolidayNZ IsBusinessDay
    24/12/2014 NULL 0 1
    25/12/2014 Christmas Day 1 0
    26/12/2014 Boxing Day 1 0
    27/12/2014 NULL 0 0
    28/12/2014 NULL 0 0
    29/12/2014 NULL 0 1
    30/12/2014 NULL 0 1
    31/12/2014 NULL 0 1
    1/01/2015 New Year's Day 1 0
    2/01/2015 Day after New Year's 1 0
    3/01/2015 NULL 0 0
    4/01/2015 NULL 0 0
    5/01/2015 NULL 0 1
    6/01/2015 NULL 0 1
    This is what I get from the query:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 0
    52 Web Sales 123457 24/12/2014 30/12/2014 0
    52 Web Sales 123458 24/12/2014 29/12/2014 0
    52 Local Market 123459 24/12/2014 29/12/2014 0
    1 Web Sale 123460 31/12/2014 5/01/2015 0
    1 Local Market 123461 31/12/2014 6/01/2015 0
    As the difference between the dispatched and open date is 2 business days or less, the result I expect is this:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 1
    52 Web Sales 123457 24/12/2014 30/12/2014 1
    52 Web Sales 123458 24/12/2014 29/12/2014 1
    52 Local Market 123459 24/12/2014 29/12/2014 1
    1 Web Sale 123460 31/12/2014 5/01/2015 1
    1 Local Market 123461 31/12/2014 6/01/2015 1
    I am using SQL Server 2012
    Thanks
    Eric

    >> The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name “isBusinessDay” but I don't know how to best use this table to calculate the On-Time metric. <<
    The Julian business day is a good trick. Number the days from whenever your calendar starts and repeat a number for a weekend or company holiday.
    CREATE TABLE Calendar
    (cal__date date NOT NULL PRIMARY KEY, 
     julian_business_nbr INTEGER NOT NULL, 
    INSERT INTO Calendar 
    VALUES ('2007-04-05', 42), 
     ('2007-04-06', 43), -- good Friday 
     ('2007-04-07', 43), 
     ('2007-04-08', 43), -- Easter Sunday 
     ('2007-04-09', 44), 
     ('2007-04-10', 45); --Tuesday
    To compute the business days from Thursday of this week to next
     Tuesdays:
    SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
     FROM Calendar AS C1, Calendar AS C2
     WHERE C1.cal__date = '2007-04-05',
     AND C2.cal__date = '2007-04-10'; 
    We do not use flags in SQL; that was assembly language. I see from your code that you are still in a 1960's mindset. You used camelCase for a column name! It makes the eyes jump and screws up maintaining code; read the literature. 
    The “#” is illegal in ANSI/ISO Standard SQL and most other ISO Standards. You are writing 1970's Sybase dialect SQL! The rest of the code is a mess. 
    The one column per line, flush left and leading comma layout tells me you used punch cards when you were learning programming; me too! We did wrote that crap because a card had only 80 columns and uppercase only IBM 027 character sets. STOP IT, it make you
    look stupid in 2015. 
    You should follow ISO-11179 rules for naming data elements. You failed. You believe that “status” is a precise, context independent data element name! NO! 
    You should follow ISO-8601 rules for displaying temporal data. But you used a horrible local dialect. WHY?? The “yyyy-mm-dd” is the only format in ANSI/ISO Standard SQL. And it is one of the most common standards embedded in ISO standards. Then you used crap
    like “6/01/2015” which is varying length and ambiguous that might be “2015-06-01” or “2015-01-06” as well as not using dashes. 
    We need to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. 
    And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> Please find below the current calculation for the On-Time Column: <<
    “No matter how far you have gone down the wrong road, turn around”
     -- Turkish proverb
    Can you throw out this mess and start over? If you do not, then be ready to have performance got to hell? You will have no maintainable code that has to be kludged like you are doing now? In a good schema an OUTER JOIN is rare, but you have more of them in
    ONE statement than I have seen in entire major corporation databases.
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Query to exclude just one day from a month/months.

    I'm sorry if a thread about this already exists i tried searching for it but couldnt find it. My question is as follows:
    I want to write a query which would fetch all the data from the month of Jun and July excluding Jun 29th. Is there a way to write a query without a subquery or function? If not then a subquery and a funtion query would work also.
    Thanks for you help.

    SQL> select date '2007-05-31' + level day from dual connect by level <= 61
      2  minus
      3  select date '2007-06-29' from dual
      4  /
    DAY
    01-06-2007 00:00:00
    02-06-2007 00:00:00
    03-06-2007 00:00:00
    04-06-2007 00:00:00
    05-06-2007 00:00:00
    06-06-2007 00:00:00
    07-06-2007 00:00:00
    08-06-2007 00:00:00
    09-06-2007 00:00:00
    10-06-2007 00:00:00
    11-06-2007 00:00:00
    12-06-2007 00:00:00
    13-06-2007 00:00:00
    14-06-2007 00:00:00
    15-06-2007 00:00:00
    16-06-2007 00:00:00
    17-06-2007 00:00:00
    18-06-2007 00:00:00
    19-06-2007 00:00:00
    20-06-2007 00:00:00
    21-06-2007 00:00:00
    22-06-2007 00:00:00
    23-06-2007 00:00:00
    24-06-2007 00:00:00
    25-06-2007 00:00:00
    26-06-2007 00:00:00
    27-06-2007 00:00:00
    28-06-2007 00:00:00
    30-06-2007 00:00:00
    01-07-2007 00:00:00
    02-07-2007 00:00:00
    03-07-2007 00:00:00
    04-07-2007 00:00:00
    05-07-2007 00:00:00
    06-07-2007 00:00:00
    07-07-2007 00:00:00
    08-07-2007 00:00:00
    09-07-2007 00:00:00
    10-07-2007 00:00:00
    11-07-2007 00:00:00
    12-07-2007 00:00:00
    13-07-2007 00:00:00
    14-07-2007 00:00:00
    15-07-2007 00:00:00
    16-07-2007 00:00:00
    17-07-2007 00:00:00
    18-07-2007 00:00:00
    19-07-2007 00:00:00
    20-07-2007 00:00:00
    21-07-2007 00:00:00
    22-07-2007 00:00:00
    23-07-2007 00:00:00
    24-07-2007 00:00:00
    25-07-2007 00:00:00
    26-07-2007 00:00:00
    27-07-2007 00:00:00
    28-07-2007 00:00:00
    29-07-2007 00:00:00
    30-07-2007 00:00:00
    31-07-2007 00:00:00
    60 rijen zijn geselecteerd.Regards,
    Rob.

  • How to calculate number of days from a date field

    Dear BW Experts.
    I have a field 'Create Date' in the BEx query. Now we need to create a variable which should give the number of days from the date of running the query (sy-datum) to the Create Date.
    This will help the users to get records which are say, 30 days old (Sy-datum - create date = 30) or 10 days old etc.
    Could you suggest as to how to create this variable.
    Thanks,
    Sai

    Hi,
    Step 1: Create variable on "Create Date" with User entry processing type
    Step 2: Create a restricted KF for Sales & restrict it on "Create Date" to get "Sales on day"
    Step 3: Manipulate  the values of "Create Date" on which you could restrict  "Sales" again and again to get other values
    Step 4: Create one variable (ZPUTMNTH) for u201CMonth to Dateu201D with processing by u201CCustomer Exitu201D. This variable was created  on u201CDateu201D characteristics.
    Step 5 : Goto C-mod t-code and use EXIT_SAPLRRS0_001
    to calculate "month to date" user input is "Calday" Key Date
    WHEN 'ZPUTMNTH'.
    IF I_STEP = 2. "after the popup
    LOOP AT I_T_VAR_RANGE INTO LOC_VAR_RANGE
    WHERE VNAM = 'ZPDATE'.
    CLEAR L_S_RANGE.
    L_S_RANGE-LOW = LOC_VAR_RANGE-LOW(6). "low value, e.g.YYYYMM (200606) part of key date (20060625)
    L_S_RANGE-LOW+6(2) = '01'. u201C low value e..g. YYYYMM01 (20060601)
    L_S_RANGE-HIGH = LOC_VAR_RANGE-LOW. "high value = input
    L_S_RANGE-SIGN = 'I'.
    L_S_RANGE-OPT = 'BT'.
    APPEND L_S_RANGE TO E_T_RANGE.
    EXIT.
    ENDLOOP.
    ENDIF.
    Assign if helps.....
    Regards,
    Suman

  • Informix / SQL Query to calculate Service Level Met %

    Hi,
    We have a client running UCCX 7.0 and we are upgrading it to 8.5.
    They have a custom .net application that display different stats on IP Phone. I have converted all of them except i am having problem calculating Service Level Met %
    Existing SQL query converts boolean into Float but Informix gives error that boolean can't be converted to float or integer.
    here is part of existing query (SQl Server) to calculate service level met %
    ROUND((SUM(CAST(ssl.metServiceLevel AS FLOAT))/COUNT(CAST(ssl.metServiceLevel AS FLOAT))) * 100,2) AS serviceLevelMet
    I will greatly appreciate if anyone can help converting this query into Informix query format.
    Thank you

    Hi Sonain
    Try this, it won't display a service level until you have received at least one call on the CSQ.
    SELECT csqsum.CSQName,loggedInAgents,talkingAgents,availableAgents,workingAgents,reservedAgents,servicelevel
    FROM  RtCSQsSummary csqSum left outer join
         (SELECT csqname, ROUND(sum(100 * (MetSL)/ (case when (MetSL + NotSL  = 0) then 1 else (MetSL + NotSL) end)) ) as servicelevel
            FROM(
                SELECT
                     trim( csqname) csqname
                    ,sum( case cqd.metServiceLevel when 't' then  1 else 0 end)  MetSL
                    ,sum( case cqd.metServiceLevel when 't' then 0 else 1 end) NotSL
                FROM ContactServiceQueue csq
                    inner join contactqueuedetail cqd  on cqd.targetID = csq.recordID
                    inner join contactroutingdetail crd on crd.sessionID = cqd.sessionID
                    inner join contactcalldetail ccd on crd.sessionID = ccd.sessionID
                WHERE Date(current) - Date(crd.StartDateTime ) = 0
                GROUP BY csqname
            )z
       GROUP BY z.csqname
        )y
    ON y.CSQName = csqsum.CSQName
    Please rate helpfull posts.
    Graham

  • SQL Query to Calculate Total PO Amount

    Hi,
    I'm trying to create a Purchase Order view that includes Total Po Amount. Has anyone done this before and can provide me with the SQL? Or advice on how to write the query to calculate the po_line amounts for each po number?
    I've looked in the POXPOEPO.fmb form for the calculation(code) and looked at several APPS views(ie. PO_Headers_Inq_V) without any success.
    Any help would be appreciated.
    Thanks
    Tony

    Tony, I think this will help you:
    select sum(pl.unit_price * pl.quantity)
    from po_lines_all pl
    , po_headers_all ph
    where ph.segment1 = 1004257 -- po_number
    and ph.po_header_id = pl.po_header_id
    Regards,
    Ricardo Cabral

  • Error while executing SQL query -' Must Specify Table to select from'

    Hi all,
    While executing query using query generator
    it shows error message
    [Microsoft][SQL Native Client][SQL Server]Must specify table to select from.
    2). [Microsoft][SQL Nativ
    SELECT T1.ItemCode, T1.Dscription AS 'Item Description', T1.Quantity, T1.Price, T1.LineTotal,
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=-90 AND T1.LineNum=T2.LineNum) as 'BEDAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=-60 AND T1.LineNum=T2.LineNum) as 'ECSAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=7 AND T1.LineNum=T2.LineNum) as 'HECSAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=1 AND T1.LineNum=T2.LineNum) as 'VATAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=4 AND T1.LineNum=T2.LineNum) as 'CSTAmt'
    FROM dbo.[OPCH] T0  INNER JOIN PCH1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN PCH4 T2 ON T2.DocEntry=T0.DocEntry
    WHERE T0.DocDate >='[%0]' AND  T0.DocDate <='[%1]' AND T0.DocType = 'I'
    GROUP BY T1.ItemCode,T1.Dscription,T1.Quantity, T1.Price, T1.LineTotal,T0.DocEntry,T1.DocEntry,T1.LineNum,T2.LineNum
    It's executing fine in MS SQL Server Studio Management.
    Please give y'r ideas to solve the problem.
    Jeyakanthan

    try this, it works fine in my B1:
    SELECT T1.ItemCode, T1.Dscription AS 'Item Description', T1.Quantity, T1.Price, T1.LineTotal,
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=-90 AND T1.LineNum=T2.LineNum) as 'BEDAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=-60 AND T1.LineNum=T2.LineNum) as 'ECSAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=7 AND T1.LineNum=T2.LineNum) as 'HECSAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=1 AND T1.LineNum=T2.LineNum) as 'VATAmt',
    (Select SUM(T2.TaxSum) From PCH4 T2 Where T0.DocEntry=T2.DocEntry AND T2.staType=4 AND T1.LineNum=T2.LineNum) as 'CSTAmt'
    FROM dbo.OPCH T0  INNER JOIN PCH1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN PCH4 T2 ON T2.DocEntry=T0.DocEntry
    WHERE T0.DocDate >='[%0]' AND  T0.DocDate <='[%1]' AND T0.DocType = 'I'
    GROUP BY T1.ItemCode,T1.Dscription,T1.Quantity, T1.Price, T1.LineTotal,T0.DocEntry,T1.DocEntry,T1.LineNum,T2.LineNum
    B1 don't like brackets!
    Regards

  • Oracle SQL query for getting specific special characters from a table

    Hi all,
    This is my table
    Table Name- Table1
    S.no    Name
    1          aaaaaaaa
    2          a1234sgjghb
    3          a@3$%jkhkjn
    4          abcd-dfghjik
    5          bbvxzckvbzxcv&^%#
    6          ashgweqfg/gfjwgefj////
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    9           dfgfdgfd"uodf
    10         aaaa  bbbbz#$
    11         cccc dddd-/mnm
    The output has to be
    S.no    Name
    3          a@3$%jkhkjn
    5          bbvxzckvbzxcv&^%#
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    10         aaaa  bbbbz#$
    It has to return "Name" column which is having special characters,whereas some special chars like -, / ," and space are acceptable.
    The Oracle query has to print columns having special characters excluding -,/," and space
    Can anyone help me to get a SQL query for the above.
    Thanks in advance.

    You can achieve it in multiple ways. Here are few.
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where regexp_like(translate(name,'a-/" ','a'), '[^[:alnum:]]');
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where translate
    19         (
    20            lower(translate(name,'a-/" ','a'))
    21          , '.0123456789abcdefghijklmnopqrstuvwxyz'
    22          , '.'
    23         ) is not null;
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL>

  • Handling sql query in jsp while extracing records from 3 tables

    hi to one and all,
    i want to implement the sql query given below in jsp in execute query statement . the query is working in sql but not when implemented using jsp. please help me in resolving this.
    Query
    SELECT e.Department , e.ETitle , s.basic , s.da, c.address1 , c.address2 from Employee e , Salary s , Contactdetails1 c where e.id = s.id and e.id =c.id

    It would help if you gave us a little more info to go on like;
    a) post your code
    b) post the error message the compiler is giving you

  • Sql query - been trying for two days

    Hi guys im trying to carry out an sql query
    Im using a left join to do a query, which gives me a set of results:
    select COURSESTUDENT.StudentNo, COURSESTUDENT.CourseCode, COURSESTUDENT.Year, MARKS.ExamMark, MARKS.EntryNo FROM COURSESTUDENT LEFT JOIN MARKS ON COURSESTUDENT.StudentNo=MARKS.StudentNo AND COURSESTUDENT.CourseCode=MARKS.CourseCode AND COURSESTUDENT.Year=MARKS.Year
    but I would like to do a select on this result but do not want to use a create view as if more than one person access this page at a time then if the servlet tries to create the view an error will occur.
    I would like to do the following select statement on the results of the query above..
    select * from (above) where CourseCode='ELE304' AND Year=1999;
    Is this possible, im using postgres..
    Please help......
    thanks
    tzaf

    just add "where ..." to the end of the first query.

  • My sql query is taking hours to run from toad

    SELECT * from (select hr.NAME org_name, ractla.org_id, acct_site.attribute_category,
              acct_site.attribute10 general_agent, arc.reversal_category,arr.reversal_gl_date,ard.reversed_source_id,
              DECODE (acct_site.attribute_category,
                      'COMM', acct_site.attribute9,
                      'IPLAN', acct_site.attribute11,
                      NULL
                     ) broker_number,                       -- changed by Michelle
              SUBSTR (hca.account_number, 1, 12) customer_number,
              ractla.attribute3 plan_type,
              SUBSTR (hp.party_name, 1, 15) customer_name,
              DECODE (ractla.attribute_category,
                      'Commercial Receivables', ractla.attribute1,
                      'Subscriber Receivables', ractla.attribute1,
                      NULL
                     ) product,                                        --x Product
              rax.trx_number trx_number, rax.trx_date transaction_date,
              DECODE
                 (SIGN (INSTR (rax.attribute4, '/')),
                  1, TO_DATE
                            (   '01'
                             || TO_CHAR
                                      (DECODE (SIGN (INSTR (rax.attribute4, '/')),
                                               1, TO_DATE
                                                         (SUBSTR (rax.attribute4,
                                                                  1,
                                                                  10
                                                          'rrrr/mm/dd'
                                               NULL
                                       'MON-RRRR'
                             'DD-MON-RRRR'
                  NULL
                 ) coverage_month, 
              DECODE (SIGN (INSTR (rax.attribute4, '/')),
                      1, TO_DATE (SUBSTR (rax.attribute4, 1, 10), 'rrrr/mm/dd'),
                      NULL
                     ) due_date,
              DECODE (acct_site.attribute_category,
                      'COMM', SUBSTR (hca.account_number, 1, 6),
                      acct_site.attribute10
                     ) employer_group,
              DECODE (arc.reversal_category,
                      'NSF', TRUNC (arr.creation_date),
                      'REV', TRUNC (arr.creation_date),
                      DECODE (arr.reversal_gl_date,
                              NULL, TRUNC (arr.apply_date),
                              DECODE (ard.reversed_source_id,
                                      NULL, TRUNC (arr.apply_date),
                                      TRUNC (arr.creation_date)
                     ) as application_date,     
                     arr.apply_date,   
                     arr.creation_date,                       --9/8/03
              arc.receipt_number receipt_number, arc.receipt_date receipt_date,
              arr.amount_applied applied_amount, rax.attribute1 company,
              rax.attribute2 division, ractla.attribute2 coverage_plan,                                                              -- (Plan Code)
              DECODE (acct_site.attribute_category,
                      'IPLAN', acct_site.attribute13,
                      'SH', acct_site.attribute8,
                      NULL
                     ) coverage_type,
              ps.amount_due_original trans_amount,
              NVL (ps.amount_due_remaining, 0) trans_amount_remaining,
              SUBSTR (hre.first_name || ' ' || hre.middle_name || ' '
                      || hre.last_name,
                      1,
                      25
                     ) salesrep_name,
              SUBSTR (acct_site.attribute5, 1, 5) salesrep_extension,
              hca.attribute4 SOURCE 
         FROM apps.ra_customer_trx_all rax,                        -- invoice info
              apps.ar_payment_schedules_all ps,
              apps.ra_cust_trx_types_all rat,
              apps.hz_cust_accounts_all hca,
              apps.hz_parties hp,
              apps.ar_receivable_applications_all arr,
              apps.ar_cash_receipts_all arc,                      --- receipt info
              apps.hr_operating_units hr,
              apps.hr_employees hre,
              apps.hz_cust_acct_sites_all acct_site,
              apps.hz_cust_site_uses_all acct_site_use,   --added by tapas on 7/16
              apps.ra_customer_trx_lines_all ractla,
              apps.ar_distributions_all ard
        WHERE
        hca.cust_account_id = rax.bill_to_customer_id 
          AND ps.customer_trx_id = rax.customer_trx_id
          AND rat.cust_trx_type_id = rax.cust_trx_type_id
          AND rat.org_id = rax.org_id
          AND arr.applied_customer_trx_id = rax.customer_trx_id
          AND arr.status = 'APP'
          AND arr.cash_receipt_id = arc.cash_receipt_id
          AND hr.organization_id = rax.org_id
          AND rax.customer_trx_id = ractla.customer_trx_id
          AND ractla.line_number = 1
          AND rax.bill_to_site_use_id = acct_site_use.site_use_id
          AND hca.cust_account_id = acct_site.cust_account_id
          AND acct_site.cust_acct_site_id = acct_site_use.cust_acct_site_id
          AND hca.party_id = hp.party_id 
          AND acct_site.attribute4 = hre.employee_id(+)
          AND hr.NAME = 'Commercial Group'
          AND ard.source_table = 'RA'
          AND ard.source_id = arr.receivable_application_id) app
          where app.application_date between :start_date and :end_Date
         and app.application_date <> app.apply_date
         and app.applied_amount>0;
    This is my query..due to some requirement i have written an inline view. The query is getting executed without inline view and even after including inline view but when i included the condition "app.applied_amount>0" its taking hours and i dont see it complete. Please advise. Urgently needed as a discoverer report needs to be built based on this.
    Thanks.
    Edited by: 958913 on Oct 8, 2012 3:52 PM
    Edited by: 958913 on Oct 8, 2012 4:19 PM
    Edited by: 958913 on Oct 8, 2012 4:33 PM

    Hi,
    the next action plan i have taken is as i need to write a condition that is based on application date(which is not a database column and is getting by a decode statement in the select) i have removed that decode statement from select and written in inline view and there by adding in where condition. Here is the query and still its taking time to run.
    /* Formatted on 2012/10/09 13:51 (Formatter Plus v4.8.8) */
    SELECT hr.NAME org_name, ractla.org_id, acct_site.attribute_category,
           acct_site.attribute10 general_agent, arc.reversal_category,
           arr.reversal_gl_date, ard.reversed_source_id,
           DECODE (acct_site.attribute_category,
                   'COMM', acct_site.attribute9,
                   'IPLAN', acct_site.attribute11,
                   NULL
                  ) broker_number,                          -- changed by Michelle
           SUBSTR (hca.account_number, 1, 12) customer_number,
           ractla.attribute3 plan_type,
           SUBSTR (hp.party_name, 1, 15) customer_name,
           DECODE (ractla.attribute_category,
                   'Commercial Receivables', ractla.attribute1,
                   'Subscriber Receivables', ractla.attribute1,
                   NULL
                  ) product,                                           --x Product
           rax.trx_number trx_number, rax.trx_date transaction_date,
           DECODE
              (SIGN (INSTR (rax.attribute4, '/')),
               1, TO_DATE (   '01'
                           || TO_CHAR (DECODE (SIGN (INSTR (rax.attribute4, '/')),
                                               1, TO_DATE
                                                         (SUBSTR (rax.attribute4,
                                                                  1,
                                                                  10
                                                          'rrrr/mm/dd'
                                               NULL
                                       'MON-RRRR'
                           'DD-MON-RRRR'
               NULL
              ) coverage_month,
           DECODE (SIGN (INSTR (rax.attribute4, '/')),
                   1, TO_DATE (SUBSTR (rax.attribute4, 1, 10), 'rrrr/mm/dd'),
                   NULL
                  ) due_date,
           DECODE (acct_site.attribute_category,
                   'COMM', SUBSTR (hca.account_number, 1, 6),
                   acct_site.attribute10
                  ) employer_group,
           app.application_date,
           arr.apply_date, arr.creation_date,                             --9/8/03
                                             arc.receipt_number receipt_number,
           arc.receipt_date receipt_date, arr.amount_applied applied_amount,
           rax.attribute1 company, rax.attribute2 division,
           ractla.attribute2 coverage_plan,                         -- (Plan Code)
           DECODE (acct_site.attribute_category,
                   'IPLAN', acct_site.attribute13,
                   'SH', acct_site.attribute8,
                   NULL
                  ) coverage_type,
           ps.amount_due_original trans_amount,
           NVL (ps.amount_due_remaining, 0) trans_amount_remaining,
           SUBSTR (hre.first_name || ' ' || hre.middle_name || ' '
                   || hre.last_name,
                   1,
                   25
                  ) salesrep_name,
           SUBSTR (acct_site.attribute5, 1, 5) salesrep_extension,
           hca.attribute4 SOURCE
      FROM apps.ra_customer_trx_all rax,                           -- invoice info
           apps.ar_payment_schedules_all ps,
           apps.ra_cust_trx_types_all rat,
           apps.hz_cust_accounts_all hca,
           apps.hz_parties hp,
           apps.ar_receivable_applications_all arr,
           apps.ar_cash_receipts_all arc,                         --- receipt info
           apps.hr_operating_units hr,
           apps.hr_employees hre,
           apps.hz_cust_acct_sites_all acct_site,
           apps.hz_cust_site_uses_all acct_site_use,      --added by tapas on 7/16
           apps.ra_customer_trx_lines_all ractla,
           apps.ar_distributions_all ard,
           (select rax1.customer_trx_id,DECODE (arc1.reversal_category,
                      'NSF', TRUNC (arr1.creation_date),
                      'REV', TRUNC (arr1.creation_date),
                      DECODE (arr1.reversal_gl_date,
                              NULL, TRUNC (arr1.apply_date),
                              DECODE (ard1.reversed_source_id,
                                      NULL, TRUNC (arr1.apply_date),
                                      TRUNC (arr1.creation_date)
                     ) as application_date
    from  apps.ar_receivable_applications_all arr1,
              apps.ar_cash_receipts_all arc1, 
              apps.ra_customer_trx_all rax1,
              apps.ar_distributions_all ard1
    where  arr1.applied_customer_trx_id = rax1.customer_trx_id
          AND arr1.status = 'APP'
          AND arr1.cash_receipt_id = arc1.cash_receipt_id
           AND ard1.source_table = 'RA'
          AND ard1.source_id = arr1.receivable_application_id
          ) app
    WHERE hca.cust_account_id = rax.bill_to_customer_id
       AND app.customer_trx_id = rax.customer_trx_id
       AND arr.apply_date <> app.application_date
       and app.application_date between :start_date and :end_date
       --AND rax.trx_number IN ('52715888', '52689753')
       AND ps.customer_trx_id = rax.customer_trx_id
       AND rat.cust_trx_type_id = rax.cust_trx_type_id
       AND rat.org_id = rax.org_id
       AND arr.applied_customer_trx_id = rax.customer_trx_id
       AND arr.status = 'APP'
       AND arr.cash_receipt_id = arc.cash_receipt_id
       AND hr.organization_id = rax.org_id
       AND rax.customer_trx_id = ractla.customer_trx_id
       AND ractla.line_number = 1
       AND rax.bill_to_site_use_id = acct_site_use.site_use_id
       AND hca.cust_account_id = acct_site.cust_account_id
       AND acct_site.cust_acct_site_id = acct_site_use.cust_acct_site_id
       AND hca.party_id = hp.party_id
       AND acct_site.attribute4 = hre.employee_id(+)
       AND hr.NAME = 'Commercial Group'
       AND ard.source_table = 'RA'
       AND ard.source_id = arr.receivable_application_id

  • Query displays no output when run from sqlplus and from procedure its displ

    Hi Guys,
    When i ran the below query, it gives me "no rows selected". I made a procedure for the below query by making it a cursor. I just tried to display the total number of records in the procedure. When ran, it showed me some number. I dont understand , why when ran just as a sql query didnt showed any output and when ran as a procedure showing some output.
    select cust_account_id
    ,related_cust_account_id
    ,object_version_number
    ,ship_to_flag
    ,status
    from apps.HZ_CUST_ACCT_RELATE re
    where
    nvl(re.bill_to_flag,'N') ='N'
    and re.customer_reciprocal_flag = 'Y'
    and re.status = 'A';
    declare
    cursor c1 is the above query
    v_count number;
    begin
    for rec in c1 loop
    v_count := v_count + 1;
    end loop;
    dbms_output.put_line(' V-Count is:' || v_count);
    end;
    also tried to print the values of the select when count is 10, it showed some values. But why is it not showing any values when ran just as a sql query.
    Help Appreciated
    Thanks

    Thanks Warren n Dmytro,
    Actually, the problem is that table has 1769645 rows of data. I wrote a cursor as defined above in a procedure. With that where condition, it doesnt have any values and so displays no rows. Its taking 5 min to run that query and get me the output.
    In the begin, I want to open that cursor using "for rec in c loop" and write one more select statement which is:
    begin
    for rec in c loop
    begin
    select count(*) into l_count
    from hz_cust_acct_relate_all
    where cust_account_id = rec.cust_account_id
    and related_cust_account_id = rec.related_cust_account_id;
    exception
    when others then
    dbms_output.put_line(-265676,"SOme err msg");
    end;
    if l_count = 0 then
    now my question is, if my cursor is not returning any rows, then the query written to get l_count will be executed or not. I am passing the cursors cust_account_id and related_cust_account_id values to this query. but that cursor is returning no data.
    so what will happen to the code that i wrote. Will it hang or will it continue. Or should i write when no_data_found exception to handle when no rows are returned.
    or can in include " exit when c%notfound after for loop". when we use open fetch and close, then we will write this exit when. can we write when using for rec in c loop syntax.
    coz when i run that procedure, it jsut hangs like that forever. how to handle it or how to tune it.
    help appreciated
    thanks

  • Sql query-filter if 1 set of data exists and in the same time 2 set doesnt

    Hi guys,
    I need to write a query where I filter on certain data being present, but in the same time other data from the same table being not present.
    For example:
    ProceduresTable:
    Type 1
    Type 1
    Type 2
    Type 2
    Type 1
    MyTable:
    Name
    OtherFields
    JoiningTable (many to many)
    ProceduresTable_Key
    MyTable_Key
    I need to select all records from MyTable and Procedures for which there are procedures from Type 1 but there are no procedures from Type 2 in the same time.
    So far I've been only able to do that by using subqueries and I think there should be an easier way to do that.
    Here is what I have:
    Select * From MyTable, Procedures, JoiningTable Where JOINING_CONDITIONS AND Type = 1 AND NAME_SOME_COLUMN NOT IN (SELECT NAME_SOME_COLUMN FROM ... WHERE Type = 2 and inner.Name = outer.Name)
    Hope you understand my meta code. I have Oracle 9 db.
    Thanks a lot!

    Hi,
    Welcome to the forum!
    Whenever you have a question, it helps if you post a specific example. Include CREATE TABLE and INSERT statements for a little sample data, and also post the results you want from that data.
    if you can use commonly available tables (like those in the scott or hr schemas) to illustrate your proble, then you don't have to post the sample data; just the results.
    For example, I think you're asking something like this:
    "How can I find information about people in the sciott.emp table who are in a department that has at least one CLERK ( that is, a row with job='CLERK') but no SALESMAN? That is, I want these results:
    {code}
    ENAME DEPTNO JOB
    CLARK 10 MANAGER
    KING 10 PRESIDENT
    MILLER 10 CLERK
    JONES 20 MANAGER
    FORD 20 ANALYST
    ADAMS 20 CLERK
    SMITH 20 CLERK
    SCOTT 20 ANALYST
    {code}
    One way is to use CASE expressions instead of WHERE clauses to test for the criteria, then using the reults of the CASE expressions in the WHERE clause.
    For example:
    WITH     got_cnts     AS
         SELECT     ename,     deptno,     job
         ,     COUNT ( CASE
                             WHEN  job = 'CLERK'
                       THEN  1
                         END
                    ) OVER (PARTITION BY deptno)     AS clerk_cnt
         ,     COUNT ( CASE
                             WHEN  job = 'SALESMAN'
                       THEN  1
                         END
                    )     OVER (PARTITION BY deptno)     AS salesman_cnt
         FROM     scott.emp
    SELECT     ename,     deptno,     job
    FROM     got_cnts
    WHERE     clerk_cnt     > 0
    AND     salesman_cnt     = 0
    ;The problem here is that you can't always tell, by looking at any one row, if it should be included or not; in this case, you need to know something about the department as a whole. Analytic functions can look at the department as a whole, but analytic functions are computed after the WHERE clause is applied, so to use the results of the analytic functions in a WHERE clause, we need to do the analytics first, in a sub-query, and the WHERE clause later.
    Sometimes (as in the example above) analytic functions are useful; other times, aggregate functions are more appropriate, depending on the exact requirements.
    Edited by: Frank Kulash on Apr 12, 2010 9:00 AM

Maybe you are looking for