Split a column based on even and odd rows

Table1
      Table2
 Col1
Odd
Even
  A
 A
  B
  B
 C
  D
  C
 E
  F
  D
 G
  H
  E
 I
NULL
  F
  G
  H
  I
I am using MS SQL v2005
I want to split a column into two columns : -
one column must have all the odd rows data while the other column must have even rows data
in other words I want the data in Table1 to be displayed as data in Table2. 
Col, Odd and Even are column names

In SQL 2005 wont approach like what I suggested do only a single scan of the table?
A major problem with your solution is that you assume that 1) the values are contiguous 2) they are numeric. Try the below:
CREATE TABLE #t (id INT NOT NULL IDENTITY(1,1), Col1 CHAR(1))
INSERT INTO #t VALUES ('A'),('B'), ('C'),('D'), ('E'),('F'), ('G'), ('H'), ('I')
go
SELECT MAX(CASE WHEN Col1 % 2 > 0 THEN Col1 END),
MAX(CASE WHEN Col1 % 2 = 0 THEN Col1 END)
FROM
SELECT Col1,ROW_NUMBER() OVER (PARTITION BY (Col1 % 2) ORDER BY Col1) AS Rn
FROM #t
)t
GROUP BY Rn
go
; WITH numbering AS (
    SELECT Col1, row_number() OVER (ORDER BY Col1) AS rowno
    FROM   #t
), leading AS (
   SELECT Col1 AS odd, LEAD(Col1) OVER(ORDER BY rowno) AS even, rowno
   FROM   numbering
SELECT odd, even
FROM   leading
WHERE  rowno % 2 = 1
go
DROP TABLE #t
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • How to work even and odd number query

    Plz explain how below worked even and odd query
    2 ) why used subquery after from and which time we can use(what time of out put)
    even
    select * FROM (SELECT ROW_NUMBER() OVER(ORDER BY stud_id) as row ,grno,stud_id from stud_Enrollment) d
     WHERE d.row %2=0   
    odd
    select * FROM (SELECT ROW_NUMBER() OVER(ORDER BY stud_id) as row ,grno,stud_id from stud_Enrollment) d
     WHERE d.row %2=1

    Row_Number function returns the sequential number of a row
    (By using partition of a result set, starting at 1 for the first row in each partition)
    >> why used subquery after from and which time we can use(what time of out put)
    When we need sequntial numbers, we can use row_number function. Put it into derived table and use this derived table after FROM clause (Same way it is used in your query)
    CREATE TABLE stud_Enrollment (
    grno int,
    stud_id int,
    stud_name varchar(20)
    INSERT INTO stud_Enrollment
    VALUES (101, 511, 'Dheeraj'), (112, 521, 'Vaibhav'), (132, 522, 'Lalit'), (124, 564, 'Amogh'), (143, 598, 'Sushrut')
    SELECT * FROM stud_Enrollment
    -- Result of your table
    --grno stud_id stud_name
    --101 511 Dheeraj
    --112 521 Vaibhav
    --132 522 Lalit
    --124 564 Amogh
    --143 598 Sushrut
    -- Now we need to find out the rows which are at even position, ie row should be at position of 0,2,4,6,8 etc..
    -- But we don't have sequential number here in your table result
    -- So we can create one new column by using row_number function
    SELECT
    ROW_NUMBER() OVER (ORDER BY stud_id) AS row, --> additiona "row" column
    grno,
    stud_id,
    stud_name
    FROM stud_Enrollment
    -- We got "row" column in below output
    --row grno stud_id stud_name
    --1 101 511 Dheeraj
    --2 112 521 Vaibhav
    --3 132 522 Lalit
    --4 124 564 Amogh
    --5 143 598 Sushrut
    -- Now above table is used after FROM clause. It uses row column in WHERE part
    SELECT
    FROM (SELECT
    ROW_NUMBER() OVER (ORDER BY stud_id) AS row,
    grno,
    stud_id,
    stud_name
    FROM stud_Enrollment) d
    WHERE d.row % 2 = 0
    --row grno stud_id stud_name
    --2 112 521 Vaibhav
    --4 124 564 Amogh
    -Vaibhav Chaudhari

  • Add Even and Odd Numbers

    I have a programming assignment that needs to read a set of integers and then finds and prints the sum of the evens and sum of the odds.
    I know how to find out which numbers are odd and even, I just can't figure out how to add up the evens and odds. Say a set of 10 integers is inputted, how can they be added up after it is determined if they are even or odd?

    Here is my code after the tip from student... It compiles but once ran it doesn't do anything after the integers are put in.
    import java.util.*;
    public class EvenOddIntegers {
        static Scanner console = new Scanner(System.in);
        static final int limit = 10;
        public static void main(String[] args) {
             int number = 0, limit = 0, sumEven = 0, sumOdd = 0;
             int odds = 0;
            int evens = 0;
             System.out.print("Enter ten positive integers: ");
             while (limit <= 10)
                  number = console.nextInt();
             if (number % 2 == 0)
                  sumEven += number;
             else if (number % 2 != 0)
                  sumOdd += number;
             System.out.println("Sum of even numbers is " + sumEven + ".");
             System.out.println("Sum of odd numbers is " + sumOdd + ".");
    }

  • Counting even and odd values

    Is there another way to count even and odd number than this one
    private static int countEvenOrOdd(int[] array, boolean countEvenNumbers){
              int count = 0;
              int remainderRequired = (countEvenNumbers ? 0 : 1);
              for(int i = 0; i < array.length; ++i){
                   if(array[i] % 2 == remainderRequired){
                        ++count;
              return count;
         }

    > I like hacking ;-) Have a look at this: ...
    Jos, you forgot the method for counting both:int countOddsAndEvens(int[] array) {
    return (countOdds(array) + countEvens(array));
    } ; )Yep, you're right, and for completeness reason I'd like to add the following:int countOthers(int[] array) {
       return array.length-countOddsAndEvens(array);
    }And for those junit maniacs:boolean testCounters(int[] array) {
       return countOddsAndEvens(array)+countOthers(array) == array.length;
    }btw, the moment I posted my previous reply I realized that I could've done better:int countOdds(int[] array) {
       int c= 0;
       for (int i= 0; i < array.length; c+= array[i++]&1);
       return c;
    }kind regards,
    Jos ( <-- never has to maintain others' code ;-)

  • Zero bleed at inside page on even and odd master pages

    Hello guys!  Going directly to my question would be how to apply bleed option specifically on inside pages when working with individual master pages for master and facing pages on the main document. The thing is when I've set no bleed on inside on my Document Setup it has applied on my even and odd master pages (remembering I have individual master pages set on my document). I am not sure if I was clear enough but I keep it open for eventual comments and so on.  Thank you.

    Ok Peter. Thank you! I am posting some screen shots to help understanding.

  • How to display even and odd number ranges between two given inputs.

    Hi Every one,
    I am just started my career in sap abap and trying to find the solution for this.
    I am trying to display number range using select options, but I am getting an error "Memory low leave the transaction before taking a break".
    Example: when I give two number 2 and 10 , it should display set of all even and odd numbers in that range.
    Below is the code logic that I am using:
    data: a type i,
             b type i,
             c type i,
             d type i,
             num type i.
    select-options: in for num.
    a = inp-low.
    b=inp-high.
    c = inp-low mod 2.
    d = inp-high mod 2.
    while a <=b and c = 0.
    write: "even numbers:', a.
    b = a + 1.
    endwhile.
    while a <=b and c <> 0.
    write: "odd numbers:', b.
    b = a + 1.
    endwhile.
    Any help will be much appreciated.

    This is your logic...changed:
    data: a type i,
              b type i,
              c type i,
              d type i,
              num type i.
    data: even type i,
           odd  type i.
    select-options: in for num.
    a = in-low.
    b = in-high.
    c = a mod 2.
    if c is INITIAL. "It measn a is even
       even = a.
       odd  = a + 1.
    else.
       odd  = a.
       even = a + 1.
    endif.
    * Even
    a = even.
    while a <= b.
       write: / 'even numbers:', a.
    *  b = a + 1.
       a = a + 2. "The next even number
    endwhile.
    * Odd
    a = odd.
    while a <= b .
       write: / 'odd numbers:', a.
       a = a + 2. "The next odd number
    endwhile.

  • Split and add Even and odd numbers

    Hi All,
    I got a seven digit number any number say for example (6581231). Now i need to add even number and odd number separately.
    Output should be
    6 + 8 + 2 = 16
    5 + 1 + 3 + 1 = 10
    Thanks
    S

    Assuming the number is always 7 digits one way to do this would be:
    Data: string(7) type c,
             num type i.
             Nmod type i.
    **move the number to a string.
    Move num to string.
    split into 7 individual chars.
    Num1 = string+1
    Num2 = string+2.
    Num3 = string+3
    Etc…
    divide each by 2 and find remainder
    Nmod = num  mod 2.
    if remainder is 0, number is even
    If nmod = 0.
    Number is even.
    Else.
    Number is odd.
    Endif.

  • CSS Even and Odd VLANS

    On the Catalyst 5000 architecture, all Even VLANs are running on one BUS on the backplane and all the odd VLANs are running on the other BUS on the backplane. Is CSS work in the same way? Hence, is it going to be a problem if I have all Even VLANs or all Odd VLANs?
    Thanks,
    /david

    David,
    The CSS does not work in this manner so your vlans can be odd or even and have not effect on the css. The only thing to keep in mind is that ever 4 ports, 1-4, 5-8, 9-12, etc.. are on separate EPIFs. So when doing network planning, you may want to consider separating connections.
    For example, if you are only using a few ports on a CS150, it would be beneficial to use ports 1,5 and 9 as they are all on different EPIFs.
    Regards
    Pete Knoops
    Cisco Systems

  • Detecting even and odd numbers

    Hi, I'm drawing a series of rectangles using AS3, and need
    every alternate one to be lighter... I'm using a switch statement
    currently, with a variable counting the number of rectangles and
    case 1, case 2, case 3, etc.
    Is there a formula or some way of telling whether there is an
    even or odd number of rectangles so my switch statement can just be
    case even:, case odd: ? The way I have it is fine for 10 or so
    rectangles but I'd rather make it more expandable.
    Would appreciate any suggestions

    % is a modulo operator that finds a remainder of a division.
    9%2 = 1, 9%4 = 1, but 9%3 = 0.
    In the case of odd/even numbers one can look at it as that an
    even number that leaves no remainder when divided by 2 and odd
    number is a number that leaves remaining 1 when divided by
    2.

  • Adding rows based on current and next row

    I got some excellent help on multiplying rows based on start and end date in this
    thread, resulting in the query below. It helps me follow Vehicle activity and Vehicle allocation of our vehicles day by day. Now I would like to add another feature to the query, if it is possible.
    The problem is that in our database, only actual tasks are registered, which means that the time when the vehicle is between tasks is not showing. I could of course calculate total available time per vehicle and month, but that would not tell me where the
    vehicles are waiting, when during the day, etc.
    So I would like to insert rows for when the vehicles are standing still, and the logic would be something like this:
    If vehicle number on current row equals vehicle number on the next row and End (date/time) of current row < Start (date/time) of next row, insert row after current row. Set Start=End of current row and End=Start of next row. Set From=To
    of current row and To=To of current row. Set Vehicle activity to "Not active". Finaly copy all other fields from current row.
    Is this possible to achieve in Power Query?
    Brgds,
    Caj
    let
        Source = Sql.Databases("sql10"),
        SLM = Source{[Name="SLM"]}[Data],
        dbo_V_LKPI = SLM{[Schema="dbo",Item="V_LKPI"]}[Data],
        RenamedColumns = Table.RenameColumns(dbo_V_LKPI,{{"ActualDeparture", "Start"}, {"ActualArrival", "End"}}),
         Records = Table.ToRecords(V_LocoKPI),
          DateTime.IsSameDay = (x, y) => Date.Year(x) = Date.Year(y) and Date.Month(x) = Date.Month(y) and Date.Day(x) = Date.Day(y),
          Expand = (x) => List.Generate(
              () => Record.Combine({x, [End=Date.EndOfDay(x[Start])]}),
              (record) => record[Start] <= x[End],
              (record) => let
                  NextStart = Date.StartOfDay(Date.AddDays(record[Start], 1)),
                  NextEnd = Date.EndOfDay(NextStart),
                  ThisEnd = List.Min({NextEnd, x[End]})
              in
                  Record.Combine({record, [Start=NextStart, End=ThisEnd]})),
          Transformed = List.Transform(Records, each if DateTime.IsSameDay([Start], [End]) then {_} else Expand(_)),
          Combined = List.Combine(Transformed),
          Result = Table.FromRecords(Combined)
      in
          Result
    Csten

    Here's some sample code. Again, we use List.Generate to build either a record or a list of records and then use List.Combine to bring the results back together before converting them to a table.
    let
        CombineTwoRows = (x, y) =>
            let
                combine = x[Vehicle] = y[Vehicle] and x[End] < y[Start],
                added = Record.Combine({x, [Start=x[End], End=y[Start], Active=false]}),
                result = if combine then {added, y} else {y}
            in result,
        GenerateStandingRows = (table, combine) =>
            let
                Handle = (x, y) => {x, y},
                buffered = Table.Buffer(table),
                n = Table.RowCount(buffered),
                windows = List.Generate(
                    () => {1, {buffered{0}}},
                    (x) => x{0} <= n,
                    (x) => {x{0} + 1, if x{0} < n then combine(buffered{x{0}-1}, buffered{x{0}}) else {buffered{x{0}}}},
                    (x) => x{1})
            in
                windows,
        InsertInactivity = (table) => Table.FromRecords(List.Combine(GenerateStandingRows(table, CombineTwoRows))),
        TestData = Table.FromRows({
            {1, #datetime(2014, 2, 23, 13, 0, 0), #datetime(2014, 2, 23, 13, 10, 0), true},
            {1, #datetime(2014, 2, 23, 13, 20, 0), #datetime(2014, 2, 23, 13, 30, 0), true},
            {2, #datetime(2014, 2, 23, 13, 20, 0), #datetime(2014, 2, 23, 14, 0, 0), true},
            {2, #datetime(2014, 2, 23, 14, 20, 0), #datetime(2014, 2, 23, 14, 40, 0), true},
            {2, #datetime(2014, 2, 23, 16, 0, 0), #datetime(2014, 2, 23, 17, 0, 0), true},
            {2, #datetime(2014, 2, 24, 2, 0, 0), #datetime(2014, 2, 24, 3, 0, 0), true},
            {3, #datetime(2014, 2, 24, 1, 0, 0), #datetime(2014, 2, 24, 8, 0, 0), true},
            {3, #datetime(2014, 2, 24, 9, 0, 0), #datetime(2014, 2, 24, 10, 0, 0), true}
            }, {"Vehicle", "Start", "End", "Active"})
    in
        InsertInactivity(TestData)

  • QUery retrieving based on previous and after rows.. pls help

      CREATE TABLE "POP"."RP06"
       (     "NUM" NUMBER(7,0),
         "SEQ_LINE" NUMBER(7,0),
         "CHMP" VARCHAR2(4000 BYTE)
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,1,'( ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,2,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,3,'AND ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,4,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,5,'OR ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,6,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,7,'AND /*4*/ ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,8,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,9,'OR ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,10,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,11,'AND ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,12,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,13,'OR ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,14,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,15,'OR ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,16,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,17,'AND ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,18,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,19,') ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,20,'AND /*10*/ ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,21,'ORACLE  IS  GREAT');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,22,'AND /*11*/ ');
    Insert into RP06 (NUM,SEQ_LINE,CHMP) values (100,23,'ORACLE  IS  GREAT');after inserting the rows i want to retrieve the rows as follows
    1 select the chmp which satisfied the condition if the chmp has previous row is  'AND'* and next row 'OR'* example: chmp with seq_line 4 which has previous 'AND' in seq_line 3 and 'OR' in seq_line 5. so retrieve the 4th seq_line chmp.
    ( CHMP WITH SEQ_LINE 8,12 ARE other EXAMPLES)
    2) select the chmp which satisfied the condition if the chmp has previous row is *'OR' and next row 'AND'*
    example: chmp with seq_line 10 which has previous 'OR' in seq_line 9 and 'AND' in seq_line 11. so retrieve the 10th seq_line chmp.
    ( CHMP WITH SEQ_LINE 6,16 ARE other EXAMPLES)
    Kindly help
    S

    Hi,
    You can use the analytic LAG function to get the value from the last row before a given row, and
    you can use the analytic LEAD function to get the value from the next row after a given row.
    For example:
    WITH     got_neighbors     AS
         SELECT  num, seq_line, chmp
         ,     LAG  (chmp) OVER ( PARTITION BY  num
                           ORDER BY      seq_line
                         )     AS prev_chmp
         ,     LEAD (chmp) OVER ( PARTITION BY  num
                           ORDER BY      seq_line
                         )     AS next_chmp
         FROM     rp06
    --     WHERE     ...     -- Any filtering goes here
    SELECT  num, seq_line, chmp
    FROM     got_neighbors
    WHERE     prev_chmp     LIKE 'AND %'
    AND     next_chmp     LIKE 'OR %'
    ;I assume that your real table can have many values for num, and that when you talk about the "earlier" or "next" row, you mean a row with the same num. If that's not the case, then remove "PARTITION BY num".
    Analytic functions are computed after the WHERE clause is applied, so to use the results of analytic functions in a WHERE clause, compute them first in a sub-query (such as got_neighbors), and then use them in the WHERE clause of a super-query.

  • Duplicate buttons on even and odd pages

    I would to be able to place in Acrobat on 100 facing pages document some buttons for printing and navigating but on different positions for odd and even pages. The Duplicate command does not offer any option for it. There is any available script for it? Thanks.

    Only if user written.
    You could use the template feature of Acrobat to make 2 templates, one for the odd pages and the the other for the even pages, and then overlay the template on the appropriate pages.
    Or split the PDF into odd and even pages, apply the buttons and then recombine the PDFs.

  • Split a text based on delimiter and add items to a sharepoint list using SPD workflow

    Hi All
    I have to store repeating table data into a sharepoint list. I have developed an approach to store data into a sharepoint list using web services as mentioned at
    http://www.bizsupportonline.net/infopath2007/how-to-submit-items-rows-repeating-table-infopath-sharepoint-list.htm. However this approach is working when form opened client only but when I opened it in browser this approach is giving error. Now I'm looking
    to promote repeating table data by combining items will a delimiter semi-colon (;). Please let me know how can I split the promoted field value using de-limiter and add it to a sharepoint list.
    Note:
    I'm working on SharePoint online 2010. (I don't have sharepoint on-premise, so I can't use SharePoint Object Model)
    If anybody know how to deal with this, please let me know.
    Thank you in advance.

    Hi Chuchendra,
    According to your description, my understanding is that you want to split the promoted field value in InfoPath form which was combined using semi-colon and add it to a SharePoint list.
    I recommend to submit the data to another SharePoint list first(use a column to store the value) and then create calculated columns to user formula to split the value, then use workflow to update the list where you want to add the value with the divided
    values.
    For example: the value is aa;bb;cc;dd.
    Based on the number of the semi-colons, we need to create one column to store the original value(named test for example), four calculated columns(v1,v2,v3,v4) to store the divided values and two more calculated columns(flag1,flag2) for use in the formula.
    v1: =LEFT([test],FIND(";",[test])-1)
    flag1: =RIGHT([test],LEN([test])-FIND(";",[test]))
    v2: =LEFT([flag1],FIND(";",[flag1])-1)
    flag2: =RIGHT([flag1],LEN([flag1])-FIND(";",[flag1]))
    v3: =LEFT([flag2],FIND(";",[flag2])-1)
    v4: =RIGHT([flag2],LEN([flag2])-FIND(";",[flag2]))
    We can also use Client Object Model to write code to split the value of the field.
    You can download the dll files form the link below:
    http://www.microsoft.com/en-in/download/details.aspx?id=21786
    Best regards.
    Thanks
    Victoria Xia
    TechNet Community Support

  • Even and odd counts..

    Whats the easiest way to determine if a button has been pushed and even or an odd number of times?
    Here is why I'm asking...
    If it has been pushed an even number of times than i want it to display one method, if odd I want
    it to display another method....

    Add a MouseListener to your Button and call the getClickCount() method on the MouseEvent, if the following condition is true then its an even number of clicks :
    if (Math.IEEEremainder((double)clickCount, 2.0) == 0.0)Ronny.

  • Even and odd page break

    Hi ALL
    I have a requirement in my report there are two things location with customer details and meter reading with costing Now my req is that location details should come on odd pages and starting from page 3. For meter details should come on even pages starting from page 4 can you plz help me in this
    Regards
    Prasoon

    i did not quite get what your report structure is.
    Is it something like
    -Customer
    -- Location details
    -- Meter reading
    -Customer
    -- Location details
    -- Meter readingIf so does the customer record fill pages 1 and 2?
    Does the location details always fit on one page or could per be more data than for one page?
    Does the meter-reding details always fit on one page or could per be more data than for one page?

Maybe you are looking for