Unpivot taking the last letter from the column name

Hi guys, having
DATE               Period1 Period2 Period3 Period4
01/01/2014       1.02       1.06      1.02      1.03
02/01/2014       1.06       1.05      1.04      1.06
I would like an unptivot as
01/01/2014    1        1.02
01/01/2014    2        1.06
01/01/2014    3        1.02
01/01/2014    4        1.03
02/01/2014    1        1.06
02/01/2014    2        1.05
02/01/2014    3        1.04
02/01/2014    4        1.06
But I'm wondering how can I take the last letter of the column. Maybe I should use a select case...
Any advices? Thank you   

DECLARE @Table TABLE
dt DATE,
P1 INT NULL,
P2 INT NULL,
P3 INT NULL,
P4 INt NULL
INSERT INTO @Table(dt, P1, P2, P3, P4)
VALUES('20140101',10,null,20,3);
INSERT INTO @Table(dt, P1, P2, P3, P4)
VALUES('20140102',50,25,15,5);
SELECT dt, row_number() over (partition by dt order by dt) rn,per AS DayMax FROM @Table
UNPIVOT (per FOR DayNumber IN (P1, P2, P3, P4)) AS c
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • Get the last query from the current user

    Is there a way to get the last query of the current user, so every query could be log with a database trigger?
    Let's just say I execute:
    DELETE xxxx;
    I tried :
    SELECT T.SQL_TEXT FROM V$SQLAREA T where ADDRESS=(SELECT prev_sql_addr FROM v$session where audsid=userenv('sessionid'));
    But the result of this query is :
    'SELECT T.SQL_TEXT FROM V$SQLAREA T where ADDRESS=(SELECT prev_sql_addr FROM v$session where audsid=userenv('sessionid'))'
    Is there a way to execute a query that would return :
    'DELETE xxxx'
    Thanks

    You could join SQL_ADDR in v$session with ADDRESS in v$sqlarea to determine the SID that executed that SQL statement last. Note that PREV_SQL_ADDR in v$session will indicate the previous SQL he executed. Though you would have to look at these tables very often to get all SQL statements issued. One note here, I think if a different user ran the SAME SQL with just bind var differences the SQL_AREA will only show the last user’s information that executed it.
    BTW - it will show deletes also...

  • How to get the last record from the database

    I am using MS Access database and Swings as GUI. I want to get the last record of a particular column from the table and store it as a varaible.

    Hi
    To get Last record of resultset, you have pass some parameter in constructor of CreateStatement.In such case Resultset should be scrollable and Readonly
    Example
    objStatement=objCon.createStatement ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    mwwResultSet=cwwStatement.executeQuery(mwwSqlQuery);
    while(mwwResultSet.next())
    if(mwwResultSet.isLast())
    //Fetch the required column record.
    String abc=mwwResultSet.getString(1);
    I think this will work. Try it.
    bye

  • Getting the last record from the internal table

    When we use a READ statement it always picks up the first record which fulfill its condition but in my case I want to pick up the last record that fulfills it condition
    I have a internal table like
    id     type
    N1      A
    N1      T
    N1      A
    N1      6 ----> LAST RECORD
    my code is
    read table itab wIth key id = netobjid.
    for eg if netobjid = N1 , then I want to read the last record that corresponds to N1 ie ID N1 TYPE - 6...
    How to do that?

    HI
    actually i have done same requirement like this ...
    Take  one count variable into your internal table ..you pass the number of records into cont variable for every time  u enter the loop .
    Sort the internal table with count variable descending . ( AS we cant sort the internal table with sy-tabix)
    Then use read statement with sy-index = 1 .
    USe below logic ,............
    data  :  count  type i value '0'.
    LOOP at int .
    count = count + 1 .
    endloop.
    sort int count descending .
    read int  with  index = 1 .

  • Why is your new version cutting off the last letter in the name of the addressee ??

    When I enter the name in a new email to send, eg
    David Smith<dsmith.com.au>
    After the email is sent the adressee name appears as David Smit
    This is occurring on every new email I compose.

    Does it always cut off the same length, like 38 seconds, is it a percentage thing, like it always cuts off 6.4%, or is it random?

  • Selecting the last record from a database table

    In my ABAP Program, I have to use a select statement to retrieve the last record from the database table with the same key.  In other words, the Program will get more than one hit on the database table for the selected keys and I need to retrieve values from only the last record and not the first.  I know I can use an internal table to sort the records first and then retrieve the right value.   But to make things easier, is there a SELECT statement keyword than I can use to do this in one single step?  Thanks!

    hi,
    tables:mara.
        data: begin of it_mara occurs 0,
                matnr like mara-matnr,
                meins like mara-meins,
                mtart like mara-mtart,
                end of it_mara.
    select-options:s_matnr for mara-matnr.
    select matnr
              meins
              mtart
    from mara
    into table it_mara
    where matnr in s_matnr.
    if not it_mara[] is initial.
    sort it_mara by matnr descending.
    read table it_mara index 1.
    endif.
    then you get the last record of the select statement.
    reward points if useful,
    venkat.

  • Why does safari 5.1 open with the last page from previous session?

    I don't want Safari 5.1 to open with the last page from the previous session.  How do I stop it?

    I too would like to manually or automatically open the windows and tabs I had open from the previous session, but I want to configure this per application.  In a browser for instance, I can have many windows and tabs open and it can take a lot of time to refresh them all. I would like to manually pick the windows/tabs I want to reopen. Before Lion I could restore the last session manually and I liked that ability. Firefox has a plugin for this And what if I reboot with no internet access, they all time out. With a word processor, spreadsheet, or xcode on the other hand, I like to start where I left off. Everything comes from local disk so the restart is fast. I want to control this by app, not globally. Sometime Apple can really be blind to the real needs of users, and that is to configure their envoronment the way the user needs, not the way Apple envisions the need of users.
    So Apple, please give ME the opportunity to choose the apps that auto reload the last sesion and give me a manual way to reload the last session on all apps that qualify.
    -KR

  • HT4847 I am unable to delete the last backup from icloud, i checked my all device setting but it still say "cannot delete icloud this time because it is in use,"Please tell me what should i do.

    I am unable to delete the last backup from icloud, i checked my all device setting but it still say "cannot delete icloud this time because it is in use,"Please tell me what should i do                             

    It still didn't work...
    Within this commonfiles\apple folder, there is only one folder, labeled "Internet Services." Within this folder, there are 6 folders, labeled:
    APLZOD.resources
    BookmarkDAV_client.resources
    CoreDAV.resources
    iCloud.resources
    iCloudServices.resources
    ShellStreams.resources
    Within all but CoreDAV and BookmarkDAV_client, there are multiple different folders, all labeled starting with a two letter (acronym I believe, for different languages) then .lproj (for example, a folder is labeled "ar.lproj".
    In each of the folders of APLZOD.resources, there is a file labeled "APLZODlocalized.dll."
    In all of the folders containing the multiple .lproj folders, there are likewise "name"localized.dll files contained.
    In the BookmarkDAV_client and Core DAV folders, they each contain only one file, "Info.plist"
    I attempted to delete all of these files, and still, the FileAssassin could not delete them. I unlocked one of them for instance, and I tried to delete the file myself (thru windows explorer and just clicking delete), and I still had the same issue of coming eventually to the window requesting me to "try again" to have permission.
    What can I do?? I'd like to avoid Unlocker, but if it really is a reliable and SAFE program, and someone knows a SAFE place to download it from, I'd appreciate it very much so!!
    thanks!!

  • It is required to get the result set from the last query.

    I need this SP to return the result set from the last query.
    SET QUOTED_IDENTIFIER OFF
    GO
    SET ANSI_NULLS ON
    GO
    alter        proc spQ_GetASCBillingRateIDs2
    @ScheduleID CHAR(15),
    @startdate smalldatetime,
    @enddate smalldatetime
    as
    set nocount on
    truncate table tbltmpgroup
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tbltmptbltest]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[tbltmptbltest]
    exec sp_CreateTblTmpGroup
    insert into tbltmpgroup
    SELECT DISTINCT
    case when pd.billparent = 'N' then org.eligibleorgid
    else isnull(af.parentid, org.eligibleorgid) end as billorgid,
    pd.individualbill , pd.cobrabill, pd.billparent,
    org.eligibleorgid, org.polid, org.orgpolicyid,
    pp.planid,  pp.rateid,
    ps.ascinvoicedate,
    case when ps.ascclaimfromdate > @startdate then ps.ascclaimfromdate
    else @startdate end as premiumrundayFrom,
    case when ps.ascclaimtodate < @enddate then ps.ascclaimtodate
    else @enddate end as premiumrundayTo,
    fts.effdate, fts.termdate,
    case when fts.effdate > @startdate then fts.EffDate
    else @startdate end as ascStartDate,
    case when fts.termdate < @enddate then fts.termdate
    else @enddate end as ascEndDate
    FROM premiumschedule ps (nolock)
    inner join orgpolicy org (nolock)
    on org.ascinvoicerungroup between ps.premiumrundayfrom and ps.premiumrundayto
    inner join FundingTypeStatus fts
    on fts.orgpolicyid = org.orgpolicyid
    and fts.fundtype = 'ASC'
    and ((fts.effdate between @startdate and @enddate)
    or (fts.termdate between @startdate and @enddate)
    or (fts.effdate < @startdate and fts.termdate > @enddate))
    inner join eligibilityorg o (nolock)
    on org.eligibleorgid = o.eligibleorgid
    inner join policydef pd (nolock)
    on pd.polid = org.polid
    inner join policyplans pp (nolock)
    on pp.polid = org.polid
    inner join program p (nolock)
    on pd.programid = p.programid
    left join orgaffiliation af with (nolock)
    on org.eligibleorgid = af.childid
    WHERE ps.premiumscheduleid = @ScheduleID
    AND org.orgpolicyid <> ''
    go
    SELECT DISTINCT z.rateid, e.enrollid, z.ascstartdate, z.ascenddate
    into tbltmptbltest FROM enrollment E (nolock)
    inner join tbltmpgroup z
    on e.rateid = z.rateid
    go
    CREATE UNIQUE CLUSTERED INDEX IDXTempTable  ON tbltmptbltest(enrollid)
    create index IDXTemptableDates on tbltmptbltest(ascstartdate,ascenddate)
    go
    select distinct t.*
    from tbltmpgroup t
    where rateid in (
    select distinct t.rateid from VW_ASC_Billing)
    order by billorgid
    set nocount off
    GO
    SET QUOTED_IDENTIFIER OFF
    GO
    SET ANSI_NULLS ON
    GO

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules (you have no idea).
    Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    What you did post is bad SQL. 
    The prefix “tbl-” is a design flaw called tibbling and we do not do it. We seldom use temp tables in RDBMS; it is how magnetic tape file programmers fake scratch tapes. 
    If the schema is correct, then SELECT DISTINCT is almost never used. 
    Your “bill_parent” looks like a assembly language bit flag; we never use those flags in SQL. 
    “Funding_Type_Status” is an absurd name for a table. A status is a state of being, not an entity. A type is an attribute property. So this table ought to be column that is either a “funding_type” or “funding_status” (with the time period for the state of being
    shown in other columns). But this hybrid is not possible in a valid data model. 
    Want to try again, with DDL and some specs? 
    --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

  • Last day from the list of dates

    i have a query which give me list of dates. From these list of date i want to find the last day in all months. when i am using last day fucntion i am getting last day from the sysdate and not from the list of dates generated by my query.
    the query
    (select distinct to_date(substr(batch_id,1,6),'DDMMRR') batch_id from gcon_mst_v0)
    order by batch_id desc
    i want last day from each month from the list of dates listed from the query.
    Help would be higly appriciated
    Thanks in advance

    The column is a varchar but i am convering it to get
    the list od dates as you can see in the query. i want
    all the last dates of every month from that list of
    dates for eg. below is the list of the dates i am
    getting from the query.
    7/11/2007
    7/10/2007
    7/9/2007
    7/8/2007
    7/6/2007
    7/5/2007
    7/4/2007
    7/3/2007
    7/2/2007
    7/1/2007
    6/29/2007
    6/28/2007
    6/27/2007
    6/26/2007
    6/25/2007
    6/24/2007
    6/22/2007
    6/21/2007
    6/20/2007
    6/19/2007
    6/18/2007
    6/17/2007
    6/15/2007
    6/14/2007
    6/13/2007
    6/12/2007
    6/11/2007
    6/10/2007
    6/8/2007
    6/7/2007
    6/6/2007
    6/5/2007
    6/4/2007
    6/3/2007
    6/1/2007
    5/31/2007
    5/30/2007
    5/29/2007
    5/28/2007
    5/27/2007
    5/25/2007
    5/24/2007
    5/23/2007
    5/22/2007
    5/21/2007
    5/20/2007
    5/18/2007
    5/17/2007
    5/16/2007
    5/15/2007
    5/14/2007
    5/13/2007
    5/11/2007
    5/10/2007
    5/9/2007
    5/8/2007
    5/7/2007
    5/6/2007
    5/4/2007
    5/3/2007
    5/2/2007
    5/1/2007
    4/30/2007
    4/29/2007
    4/27/2007
    4/26/2007
    4/25/2007
    4/24/2007
    4/23/2007
    4/22/2007
    4/20/2007
    4/19/2007
    4/18/2007
    4/17/2007
    4/16/2007
    4/15/2007
    4/14/2007
    4/12/2007
    4/11/2007
    4/10/2007
    4/9/2007
    4/8/2007
    4/6/2007
    4/5/2007
    4/4/2007
    4/3/2007
    4/2/2007
    4/1/2007
    3/30/2007
    3/29/2007
    3/28/2007
    3/27/2007
    3/26/2007
    i want the last date for all the months listed. that
    would be
    6/29/2007 -- last day for june
    5/31/2007-- last day for may
    4/30/2007-- last day for april
    3/30/2007-- last day for march and so on
    thankswrite query as
    SELECT LAST_DAY(TO_DATE(SUBSTR(COLUMN_NAME,X),'MM/DD/YYYY'))
    FROM TABLE_NAME

  • 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

  • Read to get the last line from a File

    Hi
    I am sending in a clarification , hoping that I get an efficient solution from the group, should somebody have come across this scenario and implemented.
    How to read or get the last line from a text file , which usually have a no of records, without actually reading or looping through all the lines
    I know there is some solution with the RandomAccessFile, but given there can be some encoding issues or so.
    Please let me know if somebody have implemented the same.
    Thanks n advance

    The character encoding could, indeed, be an issue especially with UTF-8. I think what I'd do is to create a byte array with the encoded, expected end of line sequence in it and work on the file in bytes. For example, seek to the last 100 bytes of the file, read those bytes and look for an EOL sequence backwards. If not found read the previous 100, 200, 400 bytes etc. until you do find an end of line. Then seek to after the EOL and read normally. Remember an EOL sequence might cross a boundary.
    UTF-8 would be a problem, especially with a unix format file because you might mistake part of a multi-byte sequence for '\n'. To be reliable on UTF-8 you'd need to go back three characters looking for sequence start markers (has the previous character got the top bit set, or the one before that the first two bits set, or the one before that the top three bits). Or you could just react to an encoding exception and try another position.

  • I downloaded an album from Itunes but one of the songs will only play first 4 minutes. It is the last song on the album. All other songs will play.

    I downloaded an album from i Tunes but one of the songs will only play first 4 minutes of 26 minutes and then stop. It is the last song on the album. All other songs will play. The Album is U.F.O. 2 One Hour of Space Rock.

    Jim, wanted to let you know it worked.  I deleted the entire album since it was an album only (26 minutes long) song, then I went to the home icon of iTunes store, clicked on purchased and saw previous purchases and bam, I downloaded the album again and it now works!!!  Thanks..
    Angelo

  • Iv downloaded the 0845 wizard from the App Store. Registered my details and it has been working. But for some reason it won't let me log in and keep saying failed every time I try to use it. Iv deleted and re-downloaded the app and it still says the same?

    Iv downloaded the 0845 wizard from the App Store. Registered my details and it has been working. But for some reason it won't let me log in and keep saying failed every time I try to use it. Iv deleted and re-downloaded the app and it still says the same?

    I would say to start by looking on their web site... unfortunately, that appears to be dead.
    Based on the horrible ratings on the App Store (1 star for the current version), I'm not surprised it doesn't work well.

  • Recently, U2 music appeared on my ipod without my requesting it or wanting it. I was able to delete all of the songs except for one. How do I delete the last one from my ipod? The song does not show up in iTunes when I plug my ipod into the computer.

    Recently, U2 music appeared on my ipod without my requesting it or wanting it. I was able to delete all of the songs except for one. How do I delete the last one from my ipod? The song does not show up in iTunes when I plug my ipod into the computer. The version installed on my ipod is 7.1.2(11D257).

    Hi donfrommars,
    Welcome to the Apple Support Communities!
    Please use the following article for information and instruction on deleting the U2 album from your devices and account.
    Remove iTunes gift album "Songs of Innocence" from your iTunes music library and purchases
    Have a great day,
    Joe

Maybe you are looking for

  • How do I get ios5 devices to sync their directly downloaded apps with iTunes ?

    I have an iMac /Lion, iPhone and iPad, previously on MobileMe and an iPod touch, never connected to mobile me. I have transferred MobileMe to iCloud. I have found that programs, downloaded directly to my iPad, will download to my iPhone(directly), bu

  • Is FF 3.6.19 incompatible with Mac OX 10.4.11?

    Downloaded this and now have a constant problem with it hanging, so i have to quit and restart FF; v annoying. Message in Force Quit is Firefox no responding. Wasn't a problem with the earlier version of FF and the new version is not compatible with

  • List of transparent tables

    Hi Gurus, How can I get a list of data dictionary tables by functional area SD, MM etc. Thank you ! Stefan

  • Update essbase variables with OS date

    Hi All, Is there a way to update my substitution variables according to the Operating System date? I am trying to avoid some manual process involved in maintaining the application. I am looking for any solutions out of Hyperion. Any help is appriciat

  • WSUS Contents on CM 2012R2

    We have been running CM 2012 R2 - CU2 for about 8 months and over the last 30 or so days, my WSUSContents is 70G which is almost 50% of my total drive space.  I have doubled checked everything I can think, WSUS is being configured via SCCM site SUP s