Cfspreadsheet in a query

Hi,
Maybe I am tired but I can't figure this out.  I am using cfspreadsheet to read data from a spreadsheet into a query.  That works great and I can dump out the data.  The problem is that I need to be able to use those results to compare to data on a database table.  What I need to do is do a query of queries to pull data based on a list of strings I get from the database.  The problem is that no matter what I do, the string from the database never gets formatted correctly.  This is the code I am working with:
          <cfspreadsheet 
    action="read"
          headerrow="true"
    src = "#thisDirectory#newdatafile.xls"    
    query = "newcodes"
          excludeHeaderRow = "true"> 
          <cfquery name="getcurrentcodes" datasource="#Request.maindatasource#">
                    SELECT code FROM currenttableindatabase
          </cfquery>
          <cfset oldcodelist = ValueList(getcurrentcodes.code)>
          <cfset trimmedoldcodes = Replace(oldcodelist," ","","all")>
          <cfquery name="GetNewCodes" dbtype="query">
                    SELECT newcode FROM newcodes
                    WHERE newcode NOT IN <cfqueryparam value="#trimmedoldcodes#">
          </cfquery>
It seems like such a simple thing but I either get double quotes around every item or no quotes.  I have also tried PreserveSingleQuotes.  Does anybody have any ideas.
Red

In addition to cfSearching's response, I would also point out QuotedValueList.  Instead of using ValueLIst then trying to add the quotes yourself, try QuotedValueList and see if that does the trick for you.  You can then use that value in the cfqueryparam list.
http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-6d 16.html
EDIT: forgot link to docs
Message was edited by: Sean Coyne

Similar Messages

  • Cfspreadsheet / checking for tabs in a workbook

    ColdFusion version:9.0.1 standard
    server OS: Windows 2008 R2
    webserver: Apache 2.2.19
    These forums worked great once before, hopefully we can go 2 / 2.
    I am opening a workbook, adding a header row to all the tabs, and then saving the workbook back to the directory as a different file.  My problem is that the workbook can have any various combination of tabs in it, and I don't know what ones unless I open the workbook itself.  Is there a way to read either the name of every tab in the workbook and then loop through those names (or the amount of sheets would work also).
    Code is here:
    <!--- All possible prefixes that could be in the sheet name --->
    <cfset prefixList = "10-00, 10-10, 10-20, 10-30, 10-40, 10-50">
    <!--- All possible status that could be in the sheet name --->
    <cfset statusList = "In progress,Closed">
    <cfloop list="#statusList#" index="si">
        <cfloop list="#prefixList#" index="pi">   
            <!--- Read the sheet --->
            <cfspreadsheet action="read" query="qWip" sheetName="#pi#-#si#" src="accounting/Files/wip.xls">   
         <cfset column = 1>   
         <!--- create new sheet with old information --->
      <cfset sObj = spreadsheetNew("#pi#-#si#")>   
      <cfset SpreadsheetAddRow(sObj, "Header")>
            <!--- add column header to all rows --->
            <cfloop from="#column#" to="#listLen(qWip.columnList)#" index="i">
       <cfset spreadsheetSetCellFormula(sObj, "CONCATENATE(""job""&#i#)", 1 , #i#)>
            </cfloop>
         <cfset SpreadsheetAddRows(sObj, qWip)>   
         <!--- dump excel file back into directory with new row header --->
            <cfspreadsheet action="update" name="sObj" filename="accounting/Files/wipHeader.xls">   
        </cfloop>
    </cfloop>
    The error comes up when a sheet does not exist in the cfspreadsheet read action.  Example:  10-10-In progress does not exist.
    Any help is appreciated.

    It seems like you could do this pretty easily by tapping into the methods for the POI HSSFWorkbook:
    <cfset workbook  = myspreadsheetobject.getworkbook()>
    You can get the number of sheets in your workbook object like so:
    <cfset numsheets = workbook.getNumberOfSheets()>
    And check for the existence of a sheet by checking:
    <cfset thesheet = workbook.getSheet(name or index)>
    You'll obviously have to work these into your logic, but I think they're a good place to start. And of course, be sure to dump out the workbook object above--you'll see all the methods available (there may be some in there that are more useful than the ones I highlighted...i only briefly looked at it)
    Hope that helps.

  • Can you specify the columns that get written to a spreadsheet when using the query attribute of cfspreadsheet?

    Hello, I wanted to see if you can control which columns from a query get written to a excel spreadsheet. I have some items in my query that I do not want in the spreadsheet but need for my query, if that makes sense.
    Thanks.
    Steve

    There are no parameters in the cfSpreadsheet tag to choose specific columns, however you can use a query of queries (About Query of Queries - ColdFusion English Documentation - Adobe Learning Resources) to get a query object with a subset of columns to pass to the tag.

  • How get cfspreadsheet to return the query dump in Excel?

    I read my data as shown in examples, but my data just displays the query dump. If I add cfheader and cfcontent, the query dump just displays in an Excel.
    I'm using CF 9.01 and Excel 2007
    shell. Here is my  code:
                <cfscript>
                                //Use an absolute path for the files. --->
                                theDir=GetDirectoryFromPath(GetCurrentTemplatePath());
                                theFile=theDir & "TrackEverythingXLS.xls";
                                //Create two empty ColdFusion spreadsheet objects. --->
                                theSheet = SpreadsheetNew("TBI_2009"); 
                                theSheet2 = SpreadsheetNew("TBI_2008");
                                //Populate each object with a query. --->
                                 SpreadsheetAddRows(theSheet,QO_getAllData); 
                                 SpreadsheetAddRows(theSheet2,QO_getAllData_TBI_2008);
                            </cfscript>                   
                            <!--- Write the sheet --->
                        <cfspreadsheet action="write" filename="#theFile#" overwrite="true"  name="theSheet"
                            sheetname="QO_getAllData"> 
                            <cfspreadsheet action="update" filename="#theFile#"  name="theSheet2" 
                            sheetname="QO_getAllData_TBI_2008">   
                          <cfheader name="Content-Disposition" value="inline; filename=TrackEverythingXLS.xls">
                            <cfcontent type="application/vnd.msexcel"> 
                             <cfspreadsheet action="read" src="#theFile#" sheetname="QO_getAllData"
                            query="spreadsheetData">
                            <cfspreadsheet action="read" src="#theFile#" sheetname="QO_getAllData_TBI_2008"
                            query="spreadsheetData2">
                           <cfdump var="#spreadsheetData#" />
                            <cfdump var="#spreadsheetData2#" />
    As you can see, I'm trying to write 2 tabs. That doesn't work either. All the data is dumped into one tab.

    My initial problem may start with "Simply create your spreadsheet as usual." How do I do that?
    With the code I just tried below, I did get a spreadsheet. So using cfheader and cfcontent is correct?
    I did not get 2 sheets though.
        <cfscript>
                                //Use an absolute path for the files. --->
                                theDir=GetDirectoryFromPath(GetCurrentTemplatePath());
                                theFile=theDir & "TrackEverythingXLS.xls";
                                //Create two empty ColdFusion spreadsheet objects. --->
                                theSheet = SpreadsheetNew("TBI_2009"); 
                                 SpreadsheetAddRows(theSheet,QO_getAllData);
                                     //Create a new sheet.
                                SpreadsheetCreateSheet (theSheet, "QO_getAllData_TBI_2008"); // 2nd query
                                //Set the sheet as active.
                                SpreadsheetSetActiveSheet (theSheet, "QO_getAllData_TBI_2008");                             
                                //Populate each object with a query. --->                             
                                 SpreadsheetAddRows(theSheet,QO_getAllData_TBI_2008);
                            </cfscript>
                            <!--- Write the sheet --->
                        <cfspreadsheet action="write" filename="#theFile#" overwrite="true"  name="theSheet"
                            sheetname="QO_getAllData">
                        <!--- (no formatting) Works best. 8/10/11 2:54 pm  --->    
                        <cfheader name="Content-Disposition" value="inline; filename=TrackEverythingXLS.xls">
                            <cfcontent type="application/vnd.msexcel">
                             <cfspreadsheet action="read" src="#theFile#" sheetname="QO_getAllData"
                            query="spreadsheetData">
                           <cfdump var="#spreadsheetData#" />
    Also, will I be able to code to Sort? Right now, I get an error message  saying: "This operation requires the merged cells to be identically  sized. (I had selected a Custom Sort on the entire sheet.) Is this a formatting issue?
    Thanks for helping me out.

  • Query results to Excel problems

    I'm trying to get results from a ColdFusion query called q to go into an Excel file.
    There are 2 things going wrong.
    1. An Excel message comes up that says "The file you are trying to open 'stc.xls', is in a different format than specified by the file extension..."
    2. character values in col1 01,02,03,... are coming over to Excel as numbers 1,2,3,...
    How do I fix those 2 things ?
    This is the way I'm trying to do it.
    <cfsetting enablecfoutputonly="yes">
    <cfcontent type="application/msexcel">
    <cfheader name="Content-Disposition" value="filename=test.xls">
    <cfoutput>
       <table>
          <cfloop index="ii" from="1" to="#q.recordcount#">
             <tr>
                <td>
                  #q.col1[ii]#
                </td>
                <td>
                  #q.col2[ii]#
                </td>
             </tr>
          </cfloop>
       </table>
    </cfoutput>

    Dan Bracuk wrote:
    Using html table tags stopped working when MS introduced Office 2007.  Use cfspreadsheet instead.
    It is not that it stopped working. Excel 2007 introduced extension hardening for increased security. So Excel warns you when the file content does not match the file extension, such as your code where cfheader claims it is an *.xls file but the content is actually html.
    Users can still open the file, they will just get a warning first. The only way to prevent the warning is to a) disable the registry setting which controls the behavior OR b) ensure the content matches the file extension. For example, generating a true Excel file with cfspreadsheet or the POIUtility.  Another option is to generate an Excel xml file. IIRC, Ben Nadels blog also has some good articles on that as well.

  • Bug in cfspreadsheet "update"?

    To those with experience with <cfspreadsheet>, I’d really appreciate your feedback. I’m trying to use the cfspreadsheet tag to generate a two page spreadsheet based on the output of two database queries. SheetOne uses "qryTopicList" and SheetTwo uses "qryTopicDetails".
    Here's my code:
    <cfscript>
    // create empty spreadsheet objects
    sheetOne = spreadsheetNew("topicList", "true");
    sheetTwo = spreadsheetNew("topicDetails", "true");
    // populate spreadsheet objects from queries
    spreadsheetAddRows(sheetOne, qrytopicList);
    spreadsheetAddRows(sheetTwo, qrytopicDetails);
    </cfscript>
    <!--- Write the two spreadsheet objects to a single file. --->
    <cfspreadsheet action="write" filename="#theFile#" name="sheetOne" sheetname="Topic List" overwrite="true" />
    <cfspreadsheet action="update" filename="#theFile#" name="sheetTwo" sheetname="Topic Details" />
    When I run this code, I get an error:
    java.lang.IllegalArgumentException: The maximum column width for an individual cell is 255 characters.
    I tracked the error down to the last line of my code which adds sheet 2. I found that the query “qrytopicDetails” has columns with more than 255 characters in them. But I know that Excel is not limited to 255 characters per cell, so I thought this might be a java/POI/ColdFusion limitation. But then I reversed the sheet order and it worked:
    <cfspreadsheet action="write" filename="#theFile#" name="sheetTwo" sheetname="Topic Details" overwrite="true" />
    <cfspreadsheet action="update" filename="#theFile#" name="sheetOne" sheetname="Topic List" />
    So, it seems that cfspreadsheet is able to "write" a column with more than 255 characters but cannot "update" if the query contains more than 255 characters. Is this a bug or am I missing something?

    Yeah, it's a bug.  Well, indeed, I can see two bugs here.
    Here's a more portable repro case:
    <cfparam name="URL.length" type="integer">
    <cfparam name="URL.xml" type="boolean">
    <cfscript>
        qrytopicList = queryNew("col1");
        queryAddRow(qrytopicList);
        querySetCell(qrytopicList, "col1", "xxx");
        qrytopicDetails = queryNew("col1");
        queryAddRow(qrytopicDetails);
        querySetCell(qrytopicDetails, "col1", repeatString("x", URL.length));
        // create empty spreadsheet objects
        sheetOne = spreadsheetNew("topicList", URL.xml);
        sheetTwo = spreadsheetNew("topicDetails", URL.xml);
        // populate spreadsheet objects from queries
        spreadsheetAddRows(sheetOne, qrytopicList);
        spreadsheetAddRows(sheetTwo, qrytopicDetails);
        if (URL.xml){
            extn = "xlsx";
        }else{
            extn = "xls";
        theFile = expandPath("./test.#extn#");
    </cfscript>
    <!--- Write the two spreadsheet objects to a single file. --->
    <cfspreadsheet action="write" filename="#theFile#" name="sheetOne" sheetname="Topic List" overwrite="true">
    <cfspreadsheet action="update" filename="#theFile#" name="sheetTwo" sheetname="Topic Details">
    This code breaks when one specifies "?length=267&xml=true" on the query string.  It's fine, however, with "?length=267&xml=false".
    So the first bug is that it breaks at all.  The second is that it's reporting 255 as some sort of significant number whereas that's not the error boundary.  And, yes, before anyone starts, I know the significance of 255, but it's not relevant to the problem here.
    As to whether it's CF or POI: dunno.
    You should raise a bug though.
    http://cfbugs.adobe.com/cfbugreport/flexbugui/cfbugtracker/main.html
    Adam

  • Cfspreadsheet and reading the xlsx files issue

    I am trying to process large excel files (65,000 rows) into the DB.  So I try to use the new cfspreadsheet tag to read in the files by 5000 rows at a time and then process the query into the tables.  The process is working fine when reading the (pre 2003 format "xls" files) but not when reading the new "xlsx" type of files.  The server is running out of memory trying to read those files for some reason.  Is this a known bug in ColdFusion 9.0??  Has anyone experiansed similar issues?
    Thanks

    if it's a POI issue (not likely, admittedly), of CF's
    usage thereof.
    If you check the POI archives, you should see a LOT of memory issues with large xlsx files. Usually related to how the file is processed. IIRC the standard way of loading a spreadsheet ie new XSSFWorkbook(name) just reads the whole file into memory in one shot. So with all the bloated xml and parsing going on it is very prone to OOM errors.
    For big files, they actually recommend using the event api instead, because of its lower footprint. I used it a couple months ago for a side project and it made a huge difference!  I did some basic profiling and the standard method (usermodel) was definitely more prone to big spikes in memory and oom errors. In contrast, memory usage with event api was far lower and more stable.
    Reason for bringing this all of this up ...? Well depending on how CF actually reads/loads spreadsheets internally, maybe the problem is a little bit of both .. ?  Just my $0.02
    -Leigh
    Message was edited by: -==cfSearching==-

  • CF10 and CFSpreadsheet

    So this is my first time using CFSpreadSheet. I'm pulling a 3500 row Excel spreadsheet in as a query. I'm the looking at the email addresses as a Valuelist and querying a database table to pull in additional elements. Then I use a query of queries to match the data and write the rows to a new Excel file. Just outputting the results to HTML is very fast, but CFSpreadsheet seems like an incredible hog! I do have some logic associated at the row level, highlighting records of a certain status.
    Does everyone have this issue? Is there any way to speed it up?
    And, when I wasn't using QoQ to match the sets, just running a query for each individual row, it would get to 575 lines and crap out with the following error.
    "String index out of range: -1 "
    Not very descriptive. It wasn't data related because I used different datasets, but it would always stop at that row count, on both my local instance on my desktop machine and on my dedicated test server as well.
    Now, since moving it to QofQ, reducing the calls to the database server to only  one, I'm getting the error repeatedly at 1347 and it still can't be attributed to a specific data record.
    String index out of range: -1
    The error occurred in C:/ColdFusion10/cfusion/wwwroot/Excel/cf~QofQExcel.cfm: line 48
    46 : 47 :      <cfset myRow = "'#myFile.ATTRIBUTE_VALUE#','#myFile.EMAIL1#','#myFile.FIRSTNAME#','#myFile.LASTNAME#','#myFile.ORDERS_ID#','#myFile.ORGNAME#','#Trim(NumbersOnly(myFile.PHONE1))#','#myFile.TIMEPLACED#','#myFile.TOTALPRODUCT#','#myFile.TOTALSHIPPING#','#myFile.TOTALTAXSHIPPING#','#getStatus.cust_name#','#getStatus.cust_num#','#getStatus.curr_order#','#getStatus.delete_date#',#DateFormat(getStatus.date_Entered,'MM/DD/YYYY')#"> 48 :      <cfset SpreadsheetAddRow(sObj, "#myRow#")> 49 :      <!--- <cfif #getStatus.curr_order# NEQ "IN"> 50 :           <cfset SpreadsheetFormatRow(sObj, {color="red"}, dataRow)>

    When in doubt, look at your data.
    Do a cfdump on the myRow Variable before you run the SpreadSheetAddRow function.  Chances are that one of your variables is an empty string.  If so, that is probably messing you up.

  • Error while running a query-Input for variable 'Posting Period is invalid

    Hi All,
    NOTE: This error is only cropping up when I input 12 in the posting period variable selection. If I put in any other value from 1-11 I am not getting any errors. Any ideas why this might be happening?
    I am getting the following error when I try and run a query - "Input for variable 'Posting Period (Single entry, mandatory)' is invalid" - On further clicking on this error the message displayed is as follows -
    Diagnosis
    Variable Posting Period (Single Value Entry, Mandatory) is used as a lower limit (X) and an upper limit () in an interval selection. This limit has the value #.
    System Response
    Procedure
    Enter a different value for variable Posting Period (Single Value Entry, Mandatory). If the value of the other limit is determined by another variable, you can change its value also.
    Procedure for System Administration

    OK.
    Well, if the variable is not used in any interval selection, then I would say "something happened to it".
    I would make a copy of the query and run it to check if I get the same problem with period 12.
       -> If not, something is wrong in the original query (you can proceed as below, if changes to original are permitted).
    If so, then try removing the variable completely from the query and hardcode restriction to 12.
       -> If problem still persists, I would have to do some thinking.
    If problem is gone, then add the variable again. Check.
       -> If problem is back, then the variable "is sick". Only quick thing to do, is to build an identical variable and use that one.
    If problem also happens with the new variable, then it's time to share this experience with someone else and consider raising an OSS.
    Good luck!
    Jacob
    P.S: what fisc year variant are you using?
    Edited by: Jacob Jansen on Jan 25, 2010 8:36 PM

  • Logical database in adhoc query

    Hello All,
    Can anyone tell me what is the logical database in adhoc query?

    Hi
    When you create a query , you have to select an infoset. Infoset can be considered as a source from which data is populated in the Query Fields.
    Infosets are created from Transaction SQ02.
    There can be four methods through which an Infoset can become a source of data:
    1.  Table join ( By joining two or more tables from Data dictionary)
         example: Joining tables PA0001 and PA0006 on Pernr to get a one resultant dataset
    2. Direct read of Basis Table ( Like PA0001 as a source for data in Infoset )
    3. Logical Database ( A Pre-written Program by SAP that extract data from clusters, tables taking care of authorizations and validity periods)
    Example : Logical database PNP, PNPCE (Concurrent Employement),PCH ( LDB for Personnel Development Data)
    Custom Logical DBs can be created in T_Code SE-36.
    4. Data Retrieval by a Program ( Custom code written by ABAP developers which will collect and process data) . This program has a corresponding Structure in data dictionary and the fields of this structure will be used in query)
    Reward Points, if helpful.
    Regards
    Waseem Imran

  • Query help on Goods Receipt Query with AP Invoice

    Looking for a little help on a query.  I would like to list all the goods receipts for a given date range and then display the AP Invoice information (if its been copied to an AP Invoice).  I think my problem is in my where clause, I plagerized an SAP query to show GR and AP from a PO as a start.  SBO 2005 SP01.  Any help would be great appreciated.  Thanks
    SELECT distinct 'GR',
    D0.DocStatus,
    D0.DocNum ,
    D0.DocDate,
    D0.DocDueDate,
    D0.DocTotal,
    'AP',
    I0.DocStatus,
    I0.DocNum ,
    I0.DocDate,
    I0.DocDueDate,
    I0.DocTotal,
    I0.PaidToDate
    FROM
    ((OPDN  D0 inner Join PDN1 D1 on D0.DocEntry = D1.DocEntry)
    full outer join
    (OPCH I0 inner join PCH1 I1 on I0.DocEntry = I1.DocEntry)
    on (I1.BaseType=20 AND D1.DocEntry = I1.BaseEntry AND D1.LineNum=I1.BaseLine))
    WHERE
    (D1.BaseType=22 AND D1.DocDate>='[%0]' AND D1.DocDate<='[%1]')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry
    FROM PDN1 WHERE BaseType=22 AND DocDate>='[%0]' AND DocDate<='[%1]'))

    Hi Dalen ,
    I  believe it is because of the condition
    (D1.BaseType=22 AND D1.DocDate>='%0' AND D1.DocDate<='%1')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry FROM PDN1 WHERE PDN1.BaseType=22 AND DocDate>='%0' AND DocDate<='%1'))
    Try changing
    D1.BaseType=22 OR D1.DocDate>='%0' AND D1.DocDate<='%1
    PDN1.BaseType=22 OR DocDate>='%0' AND DocDate<='%1'))
    Lets see what would be the result . Lets have some fun with troubleshooting
    See what would be the difference in the result .
    Thank you
    Bishal

  • Can you check for data in one table or another but not both in one query?

    I have a situation where I need to link two tables together but the data may be in another (archive) table or different records are in both but I want the latest record from either table:
    ACCOUNT
    AccountID     Name   
    123               John Doe
    124               Jane Donaldson           
    125               Harold Douglas    
    MARKETER_ACCOUNT
    Key     AccountID     Marketer    StartDate     EndDate
    1001     123               10526          8/3/2008     9/27/2009
    1017     123               10987          9/28/2009     12/31/4712    (high date ~ which means currently with this marketer)
    1023     124               10541          12/03/2010     12/31/4712
    ARCHIVE
    Key     AccountID     Marketer    StartDate     EndDate
    1015     124               10526          8/3/2008     12/02/2010
    1033     125               10987         01/01/2011     01/31/2012  
    So my query needs to return the following:
    123     John Doe                        10526     8/3/2008     9/27/2009
    124     Jane Donaldson             10541     12/03/2010     12/31/4712     (this is the later of the two records for this account between archive and marketer_account tables)
    125     Harold Douglas               10987          01/01/2011     01/31/2012     (he is only in archive, so get this record)
    I'm unsure how to proceed in one query.  Note that I am reading in possibly multiple accounts at a time and returning a collection back to .net
    open CURSOR_ACCT
              select AccountID
              from
                     ACCOUNT A,
                     MARKETER_ACCOUNT M,
                     ARCHIVE R
               where A.AccountID = nvl((select max(M.EndDate) from Marketer_account M2
                                                    where M2.AccountID = A.AccountID),
                                                      (select max(R.EndDate) from Archive R2
                                                    where R2.AccountID = A.AccountID)
                   and upper(A.Name) like parameter || '%'
    <can you do a NVL like this?   probably not...   I want to be able to get the MAX record for that account off the MarketerACcount table OR the max record for that account off the Archive table, but not both>
    (parameter could be "DO", so I return all names starting with DO...)

    if I understand your description I would assume that for John Dow we would expect the second row from marketer_account  ("high date ~ which means currently with this marketer"). Here is a solution with analytic functions:
    drop table account;
    drop table marketer_account;
    drop table marketer_account_archive;
    create table account (
        id number
      , name varchar2(20)
    insert into account values (123, 'John Doe');
    insert into account values (124, 'Jane Donaldson');
    insert into account values (125, 'Harold Douglas');
    create table marketer_account (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account values (1001, 123, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('27.09.2009', 'dd.mm.yyyy'));
    insert into marketer_account values (1017, 123, 10987, to_date('28.09.2009', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    insert into marketer_account values (1023, 124, 10541, to_date('03.12.2010', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    create table marketer_account_archive (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account_archive values (1015, 124, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('02.12.2010', 'dd.mm.yyyy'));
    insert into marketer_account_archive values (1033, 125, 10987, to_date('01.01.2011', 'dd.mm.yyyy'), to_date('31.01.2012', 'dd.mm.yyyy'));
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account_archive;
    with
    basedata as (
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account_archive
    basedata_with_max_intervals as (
    select key, AccountId, MktKey, FromDt, ToDate
         , row_number() over(partition by AccountId order by FromDt desc) FromDt_Rank
      from basedata
    filtered_basedata as (
    select key, AccountId, MktKey, FromDt, ToDate from basedata_with_max_intervals where FromDt_Rank = 1
    select a.id
         , a.name
         , b.MktKey
         , b.FromDt
         , b.ToDate
      from account a
      join filtered_basedata b
        on (a.id = b.AccountId)
    ID NAME                     MKTKEY FROMDT     TODATE
    123 John Doe                  10987 28.09.2009 31.12.4712
    124 Jane Donaldson            10541 03.12.2010 31.12.4712
    125 Harold Douglas            10987 01.01.2011 31.01.2012
    If your tables are big it could be necessary to do the filtering (according to your condition) in an early step (the first CTE).
    Regards
    Martin

  • Query help : Query to get values SYSDATE-1 18:00 hrs to SYSDATE 08:00 hrs

    Hi Team
    I want the SQl query to get the data for the following comparison : -
    Order Created is a Date Column , and i want to find out all the values from (SYSDATE-1) 18:00 hours to SYSDATE 08:00 hours
    i.e.
    (SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 08:00:00.
    Regards

    Hi, Rohit,
    942281 wrote:
    If i want the data in the below way i.e.
    from (SYSDATE-1) 18:00 hours to SYSDATE 17:59 hours ---> (SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 07:59:00.If you want to include rows from exactly 18:00:00 yesterday (but no earlier), and exclude rows from exatly 08:00:00 today (or later), then use:
    WHERE   ord_dtl.submit_dt  >= TRUNC (SYSDATE) - (6 / 24)
    AND     ord_dtl.submit_dt  <  TRUNC (SYSDATE) + (8 / 24)
    So can i use the below format : -
    ord_dtl.submit_dt BETWEEN trunc(sysdate)-(6/24) and trunc(sysdate)+(7.59/24) . Please suggest . .59 hours is .59 * 60 * 60 = 2124 seconds (or .59 * 60 = 35.4 minutes), so the last time included in the range above is 07:35:24, not 07:59:59.
    If you really, really want to use BETWEEN (which includes both end points), then you could do it with date arithmentic:
    WHERE   ord_dtl.submit_dt  BETWEEN  TRUNC (SYSDATE) - (6 / 24)
                      AND         TRUNC (SYSDATE) + (8 / 24)
                                               - (1 / (24 * 60 * 60))but it would be simpler and less error prone to use INTERVALs, as Karthick suggested earlier:
    WHERE   ord_dtl.submit_dt  BETWEEN  TRUNC (SYSDATE) - INTERVAL '6' HOUR
                      AND         TRUNC (SYSDATE) + INTERVAL '8' HOUR
                                               - INTERVAL '1' SECONDEdited by: Frank Kulash on Apr 17, 2013 9:36 AM
    Edited by: Frank Kulash on Apr 17, 2013 11:56 AM
    Changed "- (8 /24)" to "+ (8 /24)" in first code fragment (after Blushadown, below)

  • Query help, subtract two query parts

    Hi,
    I am beginner of PL/SQL and have a problem I couldn’t solve:
    Table (op_list):
    Item     -     Amount -     Status
    Item1     -     10     -     in
    Item2     -     12     -     in
    Item3     -     7     -     in
    Item1     -     2     -     out
    Item2     -     3     -     out
    Item1     -     1     -     dmg
    Item3     -     3     -     out
    Item1     -     2     -     out
    Item2     -     5     -     out
    Item2     -     2     -     in
    Item3     -     1     -     exp
    Would like to get result of query (subtract amount of 'out/dmg/exp' from 'in' ):
    Item - Amount left
    Item1     -     5
    Item2     -     6
    Item3 -     3
    I wrote code that returns sum of all incoming items and sum all out/dmg/exp items, but couldn’t solve how to subtract one part of querry from another. Or maybe there is a better way. Also worried what happens if there is no 'out/dmg/exp' only 'in'
    select item.name, sum(op_list.item_amount)
    from op_list
    inner join item
    on op_list.item = item.item_id
    where op_list.status = 'in'
    group by item.name
    union
    select item.name, sum(op_list.item_amount)
    from op_list
    inner join item
    on op_list.item = item.item_id
    where op_list.status = 'out'
    or op_list.status = 'dmg'
    or op_list.status = 'exp'
    group by item.name
    Return:
    Item1     -     10      [10 in]
    Item1     -     5     [2+1+2]
    Item2     -     14     [12+2]
    Item3     -     7
    Item3     -     4     [3+1]
    Thanks in advance

    Hi,
    We can also use simple inline views to get what we need.
    select a.item,a.amount-b.amount Balance from
    (select item,sum(amount) Amount from op_list
    where status = 'in'
    group by item) a,
    (select item,sum(amount) Amount from op_list
    where status in ('out','dmg','exp')
    group by item) b
    where
    a.item=b.item
    order by item;
    ITEM       BALANCE
    Item1                      5
    Item2                      6
    Item3                      3Regards,
    Prazy

  • Query help: query to return column that represents multiple rows

    I have a table with a name and location column. The same name can occur multiple times with any arbitrary location, i.e. duplicates are allowed.
    I need a query to find all names that occur in both of two separate locations.
    For example,
    bob usa
    bob mexico
    dot mexico
    dot europe
    hal usa
    hal europe
    sal usa
    sal mexico
    The query in question, if given the locations usa and mexico, would return bob and sal.
    Thanks for any help or advice,
    -=beeky

    How about this?
    SELECT  NAME
    FROM    <LOCATIONS_TABLE>
    WHERE   LOCATION IN ('usa','mexico')
    GROUP BY NAME
    HAVING COUNT(DISTINCT LOCATION) >= 2Results:
    SQL> WITH person_locations AS
      2  (
      3          SELECT 'bob' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      4          SELECT 'bob' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      5          SELECT 'dot' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      6          SELECT 'dot' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      7          SELECT 'hal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      8          SELECT 'hal' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      9          SELECT 'sal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
    10          SELECT 'sal' AS NAME, 'Mexico' AS LOCATION FROM DUAL
    11  )
    12  SELECT  NAME
    13  FROM    person_locations
    14  WHERE   LOCATION IN ('USA','Mexico')
    15  GROUP BY NAME
    16  HAVING COUNT(DISTINCT LOCATION) >= 2
    17  /
    NAM
    bob
    salHTH!
    Edited by: Centinul on Oct 15, 2009 2:25 PM
    Added sample results.

Maybe you are looking for

  • Windows 7 apple drivers wont install on Boot Camp

    When i go to install the drivers off the disc i get this error. "An error occured installing the package. Windows Installer returned '1620'." Has anyone had this problem? please help Im on Lion and installing to windows 7 professional

  • How Do I Back Up Movies And Music I Download?

    I usually will download Movies and Music onto my Mac and then sync it up with my iPad and iPod. How do I make sure all my Movies and Music are backed-up from my Mac? Does Time Machine back this stuff up? Thanks!

  • Enterprise Search using Sharepoint Server 2007 + SAP R/3

    Hi experts, I want to achieve an enterprise search using SharePoint Server 2007 (MOSS). SharePoint includes the BDC (business data catalog) which allows you to communicate with the SAP System. I read in the Microsoft whitepapers that thereu2019s a ne

  • Report a developer

    Does anyone know how I go about reporting a developer?.... My issue, I have an application I bought through the developer's website. The software worked ok for a while, but now, has become completely unusable.... I got a response from the developer o

  • Custom Data Provider Not Registered in Report Server (Sql Server 2012)

    We have a simple test report project set up and can preview the reports with no errors or problems from the designer. We can deploy the report project, but when trying to view the reports from the browser, we get the following error: An error as occu