Using SQL to find a match in consecutive data

Hi
I am trying to find a way (within a single SQL statement if possible) that will return a value based on whether a match is found between two points of data.
Please let me demonstrate:
create table
routetest
as
select
1 routeid,
0000 routeposition,
null actiontype,
null activityid
from dual
UNION
select
1 ,1000, 'Delay', null
from dual
UNION
select
1 ,1100, 'Activity', 'Letter'
from dual
UNION
select
1 ,1200, 'Activity', 'SMS'
from dual
UNION
select
1 ,1300, 'Activity', 'Email'
from dual
UNION
select
1 ,1400, 'Activity', 'Bar'
from dual
UNION
select
1 ,1500, 'Delay', null
from dual
UNION
select
1 ,1600, 'Activity', 'SMS'
from dual
UNION
select
1 ,1700, 'Delay', null
from dual
UNION
select
1 ,1800, 'Activity', 'Letter'
from dual
UNION
select
1 ,1900, 'Activity', 'SMS'
from dual
UNION
select
1 ,2000, null, null
from dual;
select * from routetest order by 1,2
ROUTEID ROUTEPOSITION ACTIONTYPE ACTIVITYID
      1             0                     
      1          1000 Delay               
      1          1100 Activity   Letter   
      1          1200 Activity   SMS      
      1          1300 Activity   Email    
      1          1400 Activity   Bar      
      1          1500 Delay               
      1          1600 Activity   SMS      
      1          1700 Delay               
      1          1800 Activity   Letter   
      1          1900 Activity   SMS      
      1          2000                     
12 rows selectedReturn a value where, for startpos X does activity Y exist between X and last activity before non-activity/end.
Return
0 for no - it does not,
1 for yes, at the current position and
2 for yes, after the current position (but before before the next non-activity)
Expected results:
Startpos=0
Activity=Letter
Returns: 0
Startpos=1000
Activity=Letter
Returns: 2
Startpos=1100
Activity=Letter
Returns: 1
Startpos=1000
Activity=Bar
Returns: 2
Startpos=1100
Activity=Bar
Returns: 2
Startpos=1400
Activity=Bar
Returns: 1
Startpos=1400
Activity=Bar
Returns: 1
Startpos=1500
Activity=Letter
Returns: 0
Startpos=1600
Activity=Letter
Returns: 0
Startpos=1700
Activity=Letter
Returns: 2
Does that make any sense?
Thanks
Martin

Hi, Martin,
Thanks for posting the sample data so clearly. Could you post the results you want from that data just as clearly?
I'm fairly sure you want to compute something like grp_num in the query below, so you can tell that (for example) routepostition 1000 is in the same group as 1100, but not 1600.
I'm less sure what you want beyoned that. Also, I'm just guessing at what role routeid plays in this problem.
WITH     got_grp_num     AS
     SELECT     routetest.*
     ,     ROW_NUMBER ()      OVER ( PARTITION BY  routeid
                              ORDER BY     routeposition
           - COUNT (activityid) OVER ( PARTITION BY  routeid
                              ORDER BY     routeposition
                            )     AS grp_num
     FROM     routetest
SELECT       routeid, routeposition, actiontype, activityid
,       CASE
          WHEN  activityid   IS NULL     THEN  0
          WHEN  activityid   = 'Letter'     THEN  1
          WHEN  1 <= SUM ( CASE
                         WHEN  activityid = 'Letter'
                         THEN  1
                         END
                      ) OVER ( PARTITION BY  routeid
                            ,           grp_num
                             )          THEN 2
                              ELSE 0
       END     AS letter_code
FROM       got_grp_num
ORDER BY  routeid, routeposition
;The query above produces these results:
   ROUTEID ROUTEPOSITION ACTIONTY ACTIVI LETTER_CODE
         1             0                           0
         1          1000 Delay                     0
         1          1100 Activity Letter           1
         1          1200 Activity SMS              2
         1          1300 Activity Email            2
         1          1400 Activity Bar              2
         1          1500 Delay                     0
         1          1600 Activity SMS              0
         1          1700 Delay                     0
         1          1800 Activity Letter           1
         1          1900 Activity SMS              2
         1          2000                           0I know that's not exactly what you want, but I hope it gives you some ideas.

Similar Messages

  • Need help in using SQL in a jsp file to compare date and time

    hi every one,
    Actually I am doing a project using JSP. I need to compare a date field in the database (MS Acess) to the current system date and time. I have to do this in a select statement.
    I have alredy defined a variable of type Date in the JSP file and I am comparing this variable to the date in the database through a select statemant.
    Here is what I am doing
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
              java.util.Date today = new java.util.Date();
              String myDate=sdf.format(today);
    query = "SELECT Car_ID, Model_ID, Year, Ext_Color, Price from Cars where EDate <= "+myDate+" ;";
    EDate is the feild in the database and it's format is (5/12/2008 5:29:47 PM) it is of type Date/Time in MS Acess.
    when I execute the query it gives the following error
    SQL error:java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'EDate <= 2008-10-16 08:10:07'.
    I hope any one can help me with that error and answer my question, I've tried too many things but nothing helps
    Thanks in advance :-)

    Hi,
    When the comparision is needed to be done with the current date , we don't need to send in Java
    Date then format it and compare with MS Acess Date.
    In MS Access we have Date() function which will give you the current date.
    So you can try rewriting your query as following :
    query = "SELECT Car_ID, Model_ID, Year, Ext_Color, Price from Cars where EDate <= Date() ;"; ---------------------
    Hope this helps.
    Thanks

  • How to use SQL to display Datethat falls between the date range

    Hi,
    I'm figuring out how do i use SQL to select data
    that falls between the date range stated
    (for eg. 19/02/1955 to 19/02/2003)
    I've tried :
    sql="Select * From StudentRecords WHERE DOB BETWEEN #" jTextField21.getText() "#" +" And " +"#" +jTextField22.getText;
    Using BETWEEN statment , but Between Statement isn't doing what i want..
    even those out of range are displayed... any ideas how??
    Thank yOU in advance!

    oracle:
    sql = "Select * From StudentRecords WHERE DOB between TO_DATE('07/04/2003','dd/mm/yyyy') and TO_DATE('08/04/2003','dd/mm/yyyy')";

  • Using grep to find one match per line

    Hi,
    How do you get grep to return a single line even when multiple matches are found on the same line?
    I tried the (?-m) and (?-s) without success.
    eg. searching for the string "sin" in the following line should return only one result not 2.
    SG SIN Singapore
    I don't want the search to stop after a single match, it should continue on successive lines
    Thanks,
    SB

    Sure. Let GREP find an entire line at once:<br /><br />>^.*sin.*$<br /><br />But it won't work, I'm afraid. You insist that looking for "sin" <br />i will find <br />a match in "SG SIN Singapore"; and not one but two. It won't. Try it.<br /><br /><pre> __<br />(..)<br /> _\</pre><br />Got that? So use the 'case insensitive' switch<br /><br />>(?i)^.*sin.*$<br /><br />or (perhaps better, in this case), as you seem to search for the three letter codes, use<br /><br />>^.*\<SIN\>.*$

  • How to use sql:query/ tag to retrive the system date?

    hi all,
    i want to know if i can use the <sql:query/> tag in jstl to get the database server time. please send me a code snippet to retrive n display the result. i'm new to jstl tags. please help.
    thank you,
    AM

    Check out the first hits: http://www.google.com/search?q=jstl+sql+tutorial+site:sun.com

  • Using SQL queries via ODBC connection to obtain data for a report

    Post Author: adhiann
    CA Forum: General
    Hi All,
    I was trying to run a Crystal Reports report through Clearquest using an SQL query I designed in CQ to give me the data I need, however, from within ClearQuest, I cannot associate an SQL query on a report, so I went directly to Crystal Reports and am using the ODBC connection to the ClearQuest database to run the report. I selected the right tables and fields and am using the same formula that I used on ClearQuest's SQL query to get the data, however, the report doesn't return any data whereas I am getting at least 5 records from Clearquest for the same query.
    Granted there's a difference in the way you create a SQL formula in Crystal, but I don't know if I'm doing it right as I've never had to use CR as a standalone product.
    Is there a way I can directly plug my ClearQuest's SQL query into the CR and run it? I don't know why the results won't return any data for a query that has some results
    Thanks in advance
    nandita

    Post Author: Roscoe1822
    CA Forum: General
    Did you try to add a command through the Database Expert? Also creating a Business View that contains your sql query might help as well.

  • Oracle 11g sql to find difference from two table data

    I have two tables ACTUAL AND ESTIMATE having unique column(sal_id, gal_id) and amount, tax, date columns.
    ACTUAL table
    actual_id, sal_id, gal_id, process_flag, amount, tax     date
    A1 101 201 Y 10 1 27-Aug-12
    A2 102 202 Y 20 2 27-Aug-12
    A3 102 202 N 30 3 29-Aug-12
    A4 302 402 N 40 3 30-Aug-12
    ESTIMATE table
    estimate_id, sal_id, gal_id, process_flag, amount, tax  date
    E1 301 401 Y 5 1 19-Aug-12
    E2 302 402 Y 45 4 20-Aug-12
    E3 302 402 Y 50 5 25-Aug-12
    E4 301 403 Y 10 2 27-Aug-12
    E5 301 403 N 15 3 28-Aug-12
    E6 101 201 Y 12 3 29-Aug-12
    Now My FINAL table, 1) Should have record for unprocessed (process_flag='N') from ACTUAL/ESTIMATE table for difference in amount and tax for (sal_id + gal_id) combination. If more than one processed record there, then max (date) should be consider.
    FINAL table
    actual_id, estimate_id, sal_id, gal_id, amount, tax
    A3 null 102 202 10 1 (A3-A2 actual-actual)
    A4 null 302 402 -10 -2 (A4-E3 actual-estimate with max date)
    null E5 301 403 5 1 (E5-E4 estimate-estimate)
    null E6 101 201 2 2 (E6-A1 estimate-actual)
    So basically I need a query for (A-A) U (B-B) U (A-B) U (B-A).
    I am using Oracle 11g Please help me.
    Edited by: Suresh on Aug 31, 2012 7:38 PM
    Edited by: Suresh on Aug 31, 2012 7:38 PM
    Edited by: Suresh on Aug 31, 2012 10:53 PM

    You need to provide better explanation here.A-A is always null.
    You might be looking for something like this..
    Untested version and also i cannot read your mind
    select actual_id, sal_id, gal_id, process_flag,ld_amount,ld_tax,e_date
    from(
    select actual_id, sal_id, gal_id, process_flag,e_date, amount-lead(amount) over(partition by sal_id, gal_id order by e_date desc) ld_amount,
    tax-lead(tax) over(partition by sal_id, gal_id order by e_date desc) ld_tax,
    rank()  over(partition by sal_id, gal_id order by e_date desc)rnk
    from
    (select * from actual a union
    select * from estmt e)
    ) where rnk=1

  • SQL to find the counts based on date

    Hi,
    I have a table called APP_TXN and it has application_id, application_status, created_dt columns. My job is to find out number of applications created in last 0 - 4 days, 5 - 9 days and 10 + days, group by application_status. Please help.
    Thanks & Regards,
    Christopher.

    Something like this
    select application_status,
         sum(case when created_date between sysdate-4 and sysdate then 1 else 0 end) CNT0TO4DAYS,
         sum(case when created_date between sysdate-9 and sysdate-5 then 1 else 0 end) CNT5TO9DAYS,
         sum(case when created_date <= sysdate-10 then 1 else 0 end) CNT10PLUSDAYS
       from app_txn
      group by application_status

  • Date parameter does not work in SharePoint 2010 report using SQL 2008 Server Reporting Service

    Here is the settings:
    SharePoint 2010 with SQL server 2008 reporting services configured
    When create a report for a SP list using SQL server report builder (3.0) the date parameter does not work.
    The data parameter is set as "date and time" type and field name equals the col name in the SP list
    When run the report, the whatever dates I select, the result is always the same, so the parameters do not take any effect.
    Is any step missing?
    Thanks for any advice !

    Hi ,
    How did you configure you "date and time" type parameter and field name equals the col name in the SP list?
    Have you tested if other type parameter worked?
    Have you tried typing the date format as 20140722 in your date parameter filed before run the report?
    http://whitepages.unlimitedviz.com/2012/02/using-sharepoint-filters-with-reporting-services-parameters-for-personalized-reports/
    Thanks,
    Daniel Yang
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Daniel Yang
    TechNet Community Support

  • Problem loading XML-file using SQL*Loader

    Hello,
    I'm using 9.2 and tryin to load a XML-file using SQL*Loader.
    Loader control-file:
    LOAD DATA
    INFILE *
    INTO TABLE BATCH_TABLE TRUNCATE
    FIELDS TERMINATED BY ','
    FILENAME char(255),
    XML_DATA LOBFILE (FILENAME) TERMINATED BY EOF
    BEGINDATA
    data.xml
    The BATCH_TABLE is created as:
    CREATE TABLE BATCH_TABLE (
    FILENAME VARCHAR2 (50),
    XML_DATA SYS.XMLTYPE ) ;
    And the data.xml contains the following lines:
    <?xml version="2.0" encoding="UTF-8"?>
    <!DOCTYPE databatch SYSTEM "databatch.dtd">
    <batch>
    <record>
    <data>
    <type>10</type>
    </data>
    </record>
    <record>
    <data>
    <type>20</type>
    </data>
    </record>
    </batch>
    However, the sqlldr gives me an error:
    Record 1: Rejected - Error on table BATCH_TABLE, column XML_DATA.
    ORA-21700: object does not exist or is marked for delete
    ORA-06512: at "SYS.XMLTYPE", line 0
    ORA-06512: at line 1
    If I remove the first two lines
    "<?xml version="2.0" encoding="UTF-8"?>"
    and
    "<!DOCTYPE databatch SYSTEM "databatch.dtd">"
    from data.xml everything works, and the contentents of data.xml are loaded into the table.
    Any idea what I'm missing here? Likely the problem is with special characters.
    Thanks in advance,

    I'm able to load your file just by removing the second line <!DOCTYPE databatch SYSTEM "databatch.dtd">. I dont have your dtd file, so skipped that line. Can you check if it's problem with ur DTD?

  • Force SQL Developer 1.5.4 to export data on  1 XLS workSheet

    Hello.
    I'm using SQL Developer 1.5.4 to export data into XLS format.
    The exported file is about 40MB big.
    During the export, I have noticed that SQL Developer splits the data into several worksheets, having about 64,001 rows each.
    Please, is there any way I could force SQL Developer to have all of the data on a singke WorkSheet?
    Thanks.

    I'm just guessing, but I suspect that the 64,000 row limit is so the resulting XLS file can be opened in Excel 2003 or earlier. Excel 2003 has a limit of ~65,536 (2^16) rows in a worksheet. Even if you were to export as a CSV or Text (tab-delimited) file and try loading it into Excel, it would choke and quit once the worksheet limit had been reached.
    Ed. H.

  • Need to find the assets associated to a BCC project using SQL query

    Hi,
    Given a BCC project (project_id), I need to find the assets (type of asset, version, status etc) in that project using SQL queries.
    I need this for reporting purpose and cannot do this programatically using any code.
    Surprisingly ATG does not store this association in a direct way. Can someone provide me the query if you have already done this before?
    I tried enabling loggingDebug in PublishingRepository and VersionManagerRepository to get the queries, but I did not get what I want.
    Thanks in advance,
    Gopinath Ramasamy

    UPDATE:
    When a project is selected in BCC, ATG is doing something crazy, as it appears to me, of querying all the tables (ofcourse when there is a cache miss) in all the versioned item descriptor with the workspace id of the project to display the assets contained in it.
    I do not see an easy or direct way of coming up with a query for this requirement.
    Please let me know if anyone has any other idea.
    Thanks,
    Gopinath Ramasamy

  • How to find the Navigation in peoplesoft using SQL

    Hi All ,
    I would like to know what are the possiblilites ways to find the navigation in peoplesoft.
    Is it possible to find using only RUN_CONTROL_ID same like Process name , component name ? .
    Please provide the SQL to find the possible ways.
    Advance thanks for your great help ,
    Vinoth Kumar C
    Edited by: 962735 on Mar 14, 2013 4:28 PM

    Hi Vinoth,
    Try this one..
    select distinct prcstype, ltrim (sys_connect_by_path (portal_label, ' > '), ' > ') path from (select * from (select * from psprsmdefn, ps_prcsdefnpnl where portal_name = 'EMPLOYEE' and prcsname = upper('&PrcsName')) connect by prior portal_prntobjname = portal_objname start with ( portal_uri_seg2 = pnlgrpname and portal_reftype = 'C' and portal_cref_usgt = 'TARG')) where portal_reftype = 'C' connect by portal_prntobjname = prior portal_objname start with (portal_objname = 'PORTAL_ROOT_OBJECT' and portal_reftype = 'F')
    Regards,
    Gaurav

  • I have looked through the video tutorials for CS6 and cant find any help for PHP using SQL.

    Where is a good place that I can go to learn more about using dreamweaver and different languages than html.  Is there a service that adobe offers that I could buy that would take me from rookie all the way to professional with a good easy to use structure such as adobe tv but more advanced and thorough?  I am trying to build a website with a log in page and registration.  I have the HTML part down well enough but need help writing the php scripts and using SQL to store the user info

    I'm moving this to the main Dreamweaver support forum.
    In answer to your question, you need to be aware that the PHP server behaviors in Dreamweaver CS6 use the original MySQL functions that are scheduled to be removed from a future version of PHP. The server behaviors have already been removed from Dreamweaver CC. If you are planning to create a site using PHP and MySQL, do not rely on Dreamweaver's server behaviors. You must use either MySQLi (MySQL Improved) or PDO (PHP Data Objects) instead.
    If you're looking for video tutorials, you might be interested in the courses I have created for lynda.com. As a beginner, a good place to start would be PHP for Web Designers or Introducing PHP (there are several sample videos that you can watch for free on my website). Both courses were recorded on Dreamweaver (PHP for Web Designers on Dreamweaver CS6, Introducing PHP on Dreamweaver CS5.5). PHP for Web Designers shows how to connect to MySQL with MySQLi. You need a subscription to lynda.com to watch the complete courses, but you can get a seven-day free trial by following the links on my website.
    If you don't want to commit to a subscription service, I have also written a book called PHP Solutions, which covers MySQLi and PDO in depth. It also shows how to build a login system. At the moment, the second edition is available, but a revised third edition is due to go on sale in December.
    There are also a lot of free resources on the web that you can find. The important thing to beware of is that a lot of old material relies on the original MySQL functions. Whichever resource you use, make sure it shows how to use MySQLi or PDO.

  • How to find a record then edit using sql server management studio

    Hello,
    A very basic question:
    I want to find a record stored in MS SQL Server 2008 express database table then edit the record.
    I tried to do it using SQL Server 2008 management studio express because I have been using MS Access database all the time. I have right clicked the table in management studio, clicked the "Edit top 200 records" menu item then when records were
    displayed on the result pane, I pressed Ctrl + F key to find a student named Simon for example. Well, nothing happened. I couldn't see any dialog boxes for putting in the search criteria.
    I guess I cannot simply use Ctrl+F in SQL Server management studio to find / edit a record.
    Can someone please teach me how to find a record specifying a search criteria then edit the record in SQL server management studio?

    Hi ZKM128,
    I have not seen Ctrl+F to be used to look for desired rows in Sql server.
    On the result pane after you selected "Edit top 200 records", just right click , select
    PANE, SQL, you will get the T-Sql query t,here you need to mention the exact criteria which you are looking for, and then you will get the desired rows and then you can edit.
    Thanks
    Manish
    Please use Marked as Answer if my post solved your problem and use
    Vote As Helpful if a post was useful.

Maybe you are looking for