Returning a result from multiple columns based on the last date that the column has a value.

I have this table named (pmtable)
ctrlno        jobid           docdate       work1      work2       work3
1                7              2/12/2014     20 hrs       
10 hrs
2                7             2/22/2014      35 hrs                       
15 hrs
3               7              2/28/2014                                       
12 hrs
4               8              1/17/2014      15 hrs        
13hrs
I want the result to be like this
jobid  work1    work2    work3
7        35hrs    10 hrs     12 hrs
Is this possible?

Hi serenace,
To achieve your requirement, you can reference the below.
DECLARE @Tbl TABLE(ctrlno INT,jobid INT,docdate DATE,work1 INT,work2 INT,work3 INT);
INSERT INTO @Tbl VALUES(1,7,'2/12/2014',20,10,NULL);
INSERT INTO @Tbl VALUES(2,7,'2/22/2014',35,NULL,15);
INSERT INTO @Tbl VALUES(3,7,'2/28/2014',NULL,NULL,12);
INSERT INTO @Tbl VALUES(4,8,'1/17/2014',15,13,23);
INSERT INTO @Tbl VALUES(4,8,'2/17/2014',15,NULL,NULL);
INSERT INTO @Tbl VALUES(4,8,'3/17/2014',NULL,16,NULL);
;WITH cte AS(
SELECT jobid,docdate,attr,value FROM
@Tbl
UNPIVOT
(value FOR attr IN(work1,work2,work3)) AS UT
cte2 AS(
SELECT jobid,attr,value , ROW_NUMBER() OVER(PARTITION BY jobid,attr ORDER BY docdate DESC) AS rn
from cte
SELECT jobid,ISNULL([work1],0) [work1],ISNULL([work2],0) [work2],ISNULL([work3],0) [work3] FROM
cte2
PIVOT
(SUM(value) FOR attr IN([work1],[work2],[work3])) AS PT
WHERE rn=1
If you have any question, feel free to let me know.
Eric Zhang
TechNet Community Support

Similar Messages

  • [svn:fx-trunk] 11483: Adding a LRU cache for the transcoding results of a CFF based DefineFont4 tag to avoid transcoding the same font description twice .

    Revision: 11483
    Author:   [email protected]
    Date:     2009-11-05 16:01:37 -0800 (Thu, 05 Nov 2009)
    Log Message:
    Adding a LRU cache for the transcoding results of a CFF based DefineFont4 tag to avoid transcoding the same font description twice.
    Also we now throw a better error when CFFFontManager is asked to embed a local font by name as this is not yet supported.
    QE notes: Please test that the same font embedded twice does not take twice as long as a single embedding.
    Doc notes: N/A
    Bugs:
    SDK-23966 - Compiler should generate a warning or error when embedAsCFF is true and src:local is used for font embedding
    SDK-23806 - OEM compiler appears to transcode embedded fonts twice
    SDK-23788 - Search fonts recursively
    Reviewer: Paul
    Tests run: Checkintests, bug test cases
    Is noteworthy for integration: Yes
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23966
        http://bugs.adobe.com/jira/browse/SDK-23806
        http://bugs.adobe.com/jira/browse/SDK-23788
    Modified Paths:
        flex/sdk/trunk/lib/flex-fontkit.jar
        flex/sdk/trunk/modules/swfutils/src/java/flash/fonts/FontDescription.java
        flex/sdk/trunk/modules/swfutils/src/java/flash/swf/tags/DefineFont4.java

  • Can I create a Depart Date for a record, from the Arrive Date in the next record?

    I have a Customer database with the tables tblCustomers and tblAddress. The tblCustomers has the following fields; CustomerID, CustomerName. The tblAddress has the following fields; CustomerID, Address, Town, County, ArriveDate. When a customer calls us
    we start a new record with the CustomerID, CustomerName, Address, Town, County. The ArriveDate is left blank. When my service guy calls to the customer he fills in the ArriveDate field. We do not have a LeaveDate field. He could be there from 1 day up
    to 5 days. Each day he is is there he adds another record with all the above data, including the date in the ArriveDate field. If he finishes on a Friday he will take Saturday and Sunday off. On Monday he moves to the next customer, he has a new
    customer/location record waiting for him, as before he fills in the ArriveDate and starts working. If he finishes with a customer midweek he will go straight to the next customer where there is a new customer/location record waiting for him to fill in
    the ArriveDate. It looks something along these lines;
    CustomerID    CustomerName    Address              Town               County            
     ArriveDate
    5437              Mr.A                    123 Main St       
    Nenagh            Tipperary          01/01/2015
    5437              Mr. A                   123 Main St.       Nenagh           
    Tipperary          02/01/2015
    5437              Mr. A                   123 Main St.       Nenagh            Tipperary          03/01/2015
    off Saturday and Sunday
    7890              Mr. B                   77 The Avenue    Tralee              Kerry               
    06/01/2015   
    7890              Mr. B                   77 The Avenue    Tralee             Kerry                
    07/01/2015
    I want to generate a DepartDate which will be generated when the Address, County and/or Town fields change from the previous record. The Depart Date should be equal to the last of the Arrive Dates before the Address, Town and County fields change to
    the new customer/address.
    Is this possible to do, i would appreciate any help with this.              

    Hi NewAccessLearner,
    For the results of the query, I think you accord the logic below to find the DepartDate, but the sql query would be much complex.
    Take the 123A to make a simple demo:
    #1 check the ArriveDate of the next date whether it exist in the ArriveDate
    DepartDate
    Expr1000
    t1.CustomerID
    t2.CustomerID
    Address
    Town
    County
    ArriveDate
    1/2/2015
    5437
    5437
    123 Main St
    Nenagh
    Tipperary
    1/1/2015
    1/3/2015
    5437
    5437
    123 Main St
    Nenagh
    Tipperary
    1/2/2015
    1/4/2015
    5437
    5437
    123 Main St
    Nenagh
    Tipperary
    1/3/2015
    1/8/2015
    5437
    5437
    123 Main St
    Nenagh
    Tipperary
    1/7/2015
    6/2/2015
    7890
    7890
    77 The Avenue
    Tralee
    Kerry
    6/1/2015
    In the first column the “1/4/2015” is not in the ArriveDate, and then the “1/3/2015” would be the date for DepartDate.
    I am not familiar with sql query, I think you need to ask the sql experts for help.
    Best Regards,
    Leo

  • Use the last number in a column

    Don't use spread sheets much and wondered if anybody could help with this problem. I am monitoring my weight and each day put the new weight value in the next cell. ie
    201
    198
    197
    I have another cell in the sheet which contains my target weight from which I want to subtract the latest weight record this of course moves to the next cell down each day. Is there a formula to pick the last number in a column of data? ie in the above example takes 198 on day 2 but 197 on day 3.
    Thanks
    Jonathan

    Ok. The formula didn't have to be that fancy after all. We can use COUNT to count the number of entries, then use INDEX to return the corresponding entry.
    If the actual weights are in column B and goal weight in E2, then in D2 enter this formula:
    =E2-INDEX(B,COUNT(B),1)
    So, a couple caveats:
    1) Must start entering the weights in the top body cell (whether table has header or not, see below).
    2) Column B cannot have any extraneous numbers (this will throw the count of entries off).
    Free Image Hosting
    If you are actually using Numbers '09 and the table has headers, then for some reason the formula is slightly different depending on how many header cells are in column B. E.g. if one header, then enter =INDEX(B,COUNT(B)+1,1); if two headers, then enter =INDEX(B,COUNT(B)+2,1); Or, simply enter =INDEX(B,COUNT(B)+ROW(B)-1,1), which adjusts to whatever number of header cells.
    Robin
    Message was edited by: sharknca

  • How to import the JSON data that comes from REST API into Excel 2013?

    HI,
    Is there a way to import the JSON data that REST API returns into Excel 2013? If so how?
    Could you please let me know this?
    If you need to know any more info please let me know.
    Thanks,
    Vinay

    I got this. We need to use power query add in for this.
    EXCEL 2013 -> POWER QUERY -> From Web
    Enter the URL for the REST end point and click ok. Power Query editor will show up with the URL and list of your data.
    click on the list -> Right click->drill down
    You will see the no of records the API returned.
    Right Click on List in that table -> To Table and say ok in the next dialog.
    On the displayed columns, there will be a double sided arrow, click on that and select the rows you want to import.
    There you go. You will all the data.
    Click on Apply and close. This will import the data into your excel file.

  • How to view the old data in a column if that column is dropped or rename

    Using workspace manager I am not able to track the old data of a column which is dropped.
    I have tried by using import and export features that Workspace manager have.. But import is not working properly in this case. And savepoint option is work with DML operation not with DDL.So, I want help in this matter
    Thanks In Advance

    No way even in 10g. You should build another DB and import your exported data.
    then you can get data from this new DB.
    SQL>create table t5 as select object_id,object_name,created from all_objects where rownum<20;
    Table created.
    SQL>select  current_scn from v$database;
    CURRENT_SCN
    7724122625
    SQL>desc t5
    Name                                      Null?    Type
    OBJECT_ID                                          NUMBER
    OBJECT_NAME                                        VARCHAR2(30)
    CREATED                                            DATE
    SQL>alter table t5 rename column OBJECT_ID to oid;
    Table altered.
    SQL>desc t5
    Name                                      Null?    Type
    OID                                                NUMBER
    OBJECT_NAME                                        VARCHAR2(30)
    CREATED                                            DATE
    SQL>alter table t5 drop column created;
    Table altered.
    SQL>desc t5
    Name                                      Null?    Type
    OID                                                NUMBER
    OBJECT_NAME                                        VARCHAR2(30)
    SQL>select * from t5 as of scn 7724122625;
    select * from t5 as of scn 7724122625
    ERROR at line 1:
    ORA-01466: unable to read data - table definition has changed

  • HT1277 I can send & receive email from my ipad but for some reason I can no longer do this from my i mac.It keeps telling me that the password is not valid with the imap server.I keep entering the password but it won't accept it.

    I can send & receive email from my ipad but for some reason I can no longer do this from my i mac.It keeps telling me that the password is not valid with the imap server.I keep entering the password but it won't accept it.

    Do you have one, two or more entries in the left colum of Mail.app for your mail server(s)?  That is, do you have your Mail.app set up with either a btinternet entry, with a btyahoo entry, or both?  Or more?
    I'm guessing that you might have one account (btyahoo?) listed for incoming (IMAP server) mail, and with the outbound (SMTP server) mail is configured and named btinternet.
    Based on what little I see posted, it looks like BT uses both btinternet and btyahoo, but I'm not exactly clear on how they have their stuff set up, and their web set gets helpful and tries to help configure my mail — I don't immediately see a single web page with the mail server set-up details.  The BT email client set-up starts here.

  • JSP for Vcard cannot strip carriage return in the last line of the file.

    I am using JSP to output a Vcard (http://en.wikipedia.org/wiki/VCard)
    The following code works great in Windows but fails on the mac:
    <%@ page contentType="text/x-vcard" %><%--
    --%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%--
    --%><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><%--
    --%>BEGIN:VCARD
    VERSION:2.1
    <c:choose><%--
    --%><c:when test="${not ((empty param.lan) and (empty param.fin)) }"><%--
    --%>N:${param.lan};${param.fin}
    FN:${param.fin} ${param.lan}
    </c:when><%--
    --%><c:otherwise><%--
    --%>FN:${param.org}
    </c:otherwise><%--
    --%></c:choose><%--
    --%>ORG:${param.org}
    TITLE:${param.title}
    TEL;WORK;VOICE:${param.phwork}
    ADR;WORK:;;${param.st};${param.city};${param.state};${param.zip};
    EMAIL;PREF;INTERNET:${param.email}
    REV:20080424T195243Z
    <c:out value="${fn:replace('END:VCARD','\\\r','')}" escapeXml="false"/>After some tests, I discovered that Mac (I used Tiger, latest update, not Leopard) needs extra white space and carriage returns stripped off. Once this is achieved, the vcard will automatically import into Address Book. I have followed other forums which advice on using JSP comments as in the code above. But for some strange reason the last line of the JSP outputs an extra carraige return. How do I get rid of the carriage return at the end of the file? the replace function from JSTL is not working.
    Edited by: shogo2040 on Dec 18, 2008 7:11 PM : I added more detail to the Subject

    I originally had that END:VCARD without any carriage return.
    But I still get an extra carriage return at the end when the JSP renders to VCF
    I'm using Tomcat running on Linux.
    I found this, article which implies (but does not explicitly say) JSP in general adds a newline to the last line:
    http://www.caucho.com/resin-3.0/jsp/faq.xtp (But its not tomcat either, so maybe this info is irrelevant).
    Edited by: shogo2040 on Dec 22, 2008 3:31 PM - changed rendered to VCF from rendered to JSP

  • How to find the creation date of a column in a table?

    Hi,
    i scroll all the view and table of the Oracle RDBMS catalog and i didn't find how i can find when a column has been added to a table.
    Is there a way i can find this info?
    The column added is not the same date tehn the date of the table creation or the analyse column.
    Thanks

    Hi,
    Something like this
    select table_name, created from user_objects where object_type = 'TABLE'Regards
    Anurag Tibrewal
    Oops: I did not see the requirement correctly. If auditing is not the option for you then logminer (if archive is present) else no other option i can think of.
    Edited by: Anurag Tibrewal on Oct 6, 2009 8:37 PM

  • Can I get a query to get the output data like 4th column instead of 3rd col

    Can I get a query to get the output data like 4th column instead of 3rd column ?
    SQL&gt; select emp.deptno, empno, rownum from emp, dept where emp.deptno=dept.deptno;
    DEPTNO EMPNO ROWNUM
    10 7782 *1* *1*
    10 7839 *2* *2*
    10 7934 *3* *3*
    20 7369 *4* *1*
    20 7876 *5* *2*
    20 7902 *6* *3*
    20 7788 *7* *4*
    20 7566 *8* *5*
    30 7499 *9* *1*
    30 7698 *10* *2*
    30 7654 *11* *3*
    30 7900 *12* *4*
    30 7844 *13* *5*
    30 7521 *14* *6*
    14 rows selected.

    SQL> select emp.deptno, emp.empno,
      2    row_number() over(order by emp.deptno, emp.empno) rn,
      3    row_number() over(partition by emp.deptno order by emp.empno) dept_rn
      4  from emp, dept
      5  where emp.deptno=dept.deptno
      6  order by emp.deptno, emp.empno;
        DEPTNO      EMPNO         RN    DEPT_RN
            10       7782          1          1
            10       7839          2          2
            10       7934          3          3
            20       7369          4          1
            20       7566          5          2
            20       7788          6          3
            20       7876          7          4
            20       7902          8          5
            30       7499          9          1
            30       7521         10          2
            30       7654         11          3
            30       7698         12          4
            30       7844         13          5
            30       7900         14          6
    14 rows selected.Regards,
    Dima

  • Function to find the Last Date of Month One Year Ago - RETURNS ERROR

    I've written sql code which takes a date and finds the Last Day of the Month one year ago. For example,  it takes the date '2015-04-17' and returns the date '2014-04-30'. The code works fine in a query. Now I'm trying to turn this into a function. However,
    when I try to create the function I get the error:
    Operand type clash: date is incompatible with int
    Why is this error being returned?
    Here is my function:
    CREATE FUNCTION dbo.zEOM_LY_D(@Input Date)
           RETURNS date
    AS
    BEGIN;
      DECLARE @Result date;
      SET @Result =  convert(DATE, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,dateadd(m, -11, @Input)+1),0)),101)
        RETURN @Result;
    END;
    Thanks for any help you can give.
                     

    Stan,
    Thanks very much- that does the trick. I should have said I am using SQL 2008 so EOMONTH is not available to me. I still don't get why I got an error though, since I was treating a date like a date and not like an int.
    Thanks, John
    I think i found the issue but i do not know why it is causing the issue. i think may be the way dates are treated/stored internally..i think dates are stored as no of days after 0001/01/01 but cannot see how this cwould effect..may be somebody else can through
    some light..... 
    if you make it as datetime it will work,
    if you leave it as date - eliminate adding 1...  you should prefer to use dateadd to add/substract dates.
    try this to understand..
    --removed the +1 in the code
    declare @input date
    set @input ='20150503'
    select
    convert(DATE, DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,dateadd(m, -11, @Input)),0)),101)
    go
    --made the datatype as datetime
    declare @input datetime
    set @input ='20150503'
    select
    convert(DATE, DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,dateadd(m, -11, @Input)+1),0)),101)
    Hope it Helps!!

  • Sum from current date to the last date of sales

    Hi 
    It's been a while since I used MDX last time. 
    I have a simple question (probably). I need a measure which sums up from the current date to the last sale date. 
    It's like a reversal of Year To date.  And I need to do it date level. 
    Let's say is the sales goes like
    1/May/2000     $1000
    2/May/2000     $1000
    3/May/2000     $1000
    4/May/2000     $1000
    5/May/2000     $1000
    I need to create a measure which displays sum of current sales and last sales
    1/May/2000     $5000  
    2/May/2000     $4000
    3/May/2000     $3000
    4/May/2000     $2000
    5/May/2000     $1000
    I have a date hierarchy and hope it can be rolled up. 
    And I tried like something like ( suggested in another posting)
    [Date].[Calendar].CurrentMember:NULL}
    But this does not work for me.
    The actual MDx I wrote is 
    With member MEASURES.ActiveLicences as 
    sum ( 
    {[License Expiry Date].[FinancialYear].[YY-MMM].CurrentMember: null},
    [Measures].[No of Students]
    select {
    MEASURES.ActiveLicences,
    [Measures].[No of Students] } on columns, 
    [License Expiry Date].[FinancialYear].[YY-MMM].members on rows 
    from [Sales];
    Can anyone help me with this please? 
    Kind regards
    Mark Kim

    Hi SQLMa ,
    I was trying a similar code, using a hierarchy expression instead of a member expression for the CurrentMember functionality . Here is an Adventure Works example :
    With member MEASURES.ActiveLicences as 
    sum ( {[Delivery Date].[Fiscal].CurrentMember: null}
    , [Measures].[Internet Sales Amount]) 
    select {MEASURES.ActiveLicences,[Measures].[Internet Sales Amount]} on columns
    , [Delivery Date].[Fiscal].[Month].members on rows 
    from [Adventure Works]
    Hope it helps :)
    Regards, David .

  • How do we send photos from an iphone to a business email so that the photo shows up as an attachment vs. a part of the body of the email?

    How do you email photos from an iphone to a business email so that the photo shows up as an attachment vs. a part of the body of the email?

    Eric, thanks for the info about the pictures, it worked.   The mail icon is not the one that came with the mac(it looks like a stamp with an eagle) this appears at a notepad with a ruler,paintbrush and pencil.  I can not open it, I did not download it and now I can not turn off the computer with shutdown I have to manually turn if off by pressing the power button.   This can not be normal.  Any suggestions.  thanks,  Ellen

  • I found how to delete a series from my ipad, but it still won't download the last episode of the new series I am trying to have.  What have I done wrong?

    I found how to delete a series from my ipad, but it still won't download the last episode of the new series I am trying to have.  What have I done wrong?

    What is the GarageBand version that your friend is using?
    If it is GarageBand '11, version 6.0.5, you can buy GarageBand '11 as a boxed retail version with the iLIfe '11 bundle, e.g. from Amazon.
    Then you can upgrade GarageBand '11 to 6.0.5, using this upgrader from the Support page:
                     GarageBand 6.0.5
    GarageBand 6.0.5 will work well with your system.  But if your friend is using the newest GarageBand 10, this will not help. Then ask your friend to send you audio files for each track, so you can recreate the project from the audio.  Or your friend could also use GarageBand '11 for the projects you want to share, that will run well in all newer MacOS X versions, even with GarageBand 10.0 installed on the same system.
    -- Leonie

  • I have Iphoto '09, version 8.1.2 (424). I am having an identical problem.  All my pictures are imported into Iphoto when I downloaded them from my camera.  Until recently, I thought that the pictures were actually saved in the library.  Since I need to cr

    I have Iphoto '09, version 8.1.2 (424). I am having an identical problem.  All my pictures are imported into Iphoto when I downloaded them from my camera.  Until recently, I thought that the pictures were actually saved in the library.  Since I need to crop my pictures for the web, and Iphoto doesn't do that, I purchased Photoshop Elements to do that.  To my surprise, when I try to get a picture from Iphoto to Photoshop, it can't be done. That was when I realized, after wasting a lot of time, that the photos are not in the Iphoto library.
    I started naming the pictures on Iphoto so I had a recognizable file name to open on Photoshop. Couldn't find it.  I looked in the Backup folder and the Transfer software folder (I have a Nikon camera), and the names I entered in the Iphoto display, could not be found.
    When I am trying to upload a photo to the web, I get the Finder folder showing  with an active folder called "Photos" under "Media", which only displays Iphoto and PhotoBooth.  This is a folder name that I cannot find in my HD anywhere when I look for it.  If I edit a picture with Photoshop, I am not going to save it back to Iphoto (not sure whether it will work properly).  How do I get my folder of edited photos to show when I want to upload a picture to the web?
    Where (the name of the folder) do I find the pictures I see displayed on the Iphoto library, including any name changes, keywords added, and so on?

    See my response to your other post.

Maybe you are looking for

  • Best way to spawn java processes

    I'm trying to execute several instances of a java class in seperate processes to be distributed on a cluster. for now (until i get on the cluster on monday) i am assuming my classpath and all of the data files are on an NFS storage accessible from al

  • Can it be any slower?

    I have the E4200 on a Mac.  Wireless connection.  HughesNet Internet Service.  Just downloaded the latest firmware.  Internet Speed tests consistently show (over a couple of days): Download Speed = 1.31 (Highest!) Upload Speed = 0.21 (Again, highest

  • Deleting Recents using ios8

    I. trying to modify and/or delete some of the listings in the new Recents banner that shows up noe in iOS8

  • Has anyone had any issues with the sleep indicator light?

    I have a 15.4-inch MacBook Pro 2.8 GHz (Late 2009) and recently I have noticed some issues involving the sleep indicator light and my Mac sleeping. I learned that the sleep indicator light is supposed to be on when you press the power button until th

  • All Business Partners via JCo

    Hello @all, I´m testing some things with the Business One Java Connector. At the moment I try to get a list of all Business Partners. But I can´t find a class or method I can use for. Can anyone help me? Thanks a lot.