1

Say there is a SQL Server table which contain 2 columns: ID, Value

The sample data looks like this:

ID           value
------------------    
1            30
1            30
2            50
2            50
3            50

When I run this query:

 select ID, NEWID(), value 
 from table1 
 order by ID

The result looks like this:

  1            30            E152AD19-9920-4567-87FF-C4822FD9E485
  1            30            54F28C58-ABA9-4DFB-9A80-CE9C4C390CBB
  2            50            ........
  2            50            ........
  3            50            4E5A9E26-FEEC-4CC7-9AC5-96747053B6B2

But what I want is : how many record of ID depending on (sum of value /30 )'s result, for example of ID 2, it's value's sum is 50+50=100, and 100/30=3, so ID 2 will display in query result three times

The final result i want is like this:

  1        E152AD19-9920-4567-87FF-C4822FD9E485
  1        54F28C58-ABA9-4DFB-9A80-CE9C4C390CBB
  2        4E5A9E26-FEEC-4CC7-9AC5-96747053B6B2
  2        ....
  2        ....
  3        D861563E-E01A-4198-9E92-7BEB4678E5D1

Please note ID of 2 display three times, wait for your helps, thanks.

1 Answer 1

1

How about something like

CREATE TABLE Table1
    ([ID] int, [value] int)
;

INSERT INTO Table1
    ([ID], [value])
VALUES
    (1, 30),
    (1, 30),
    (2, 50),
    (2, 50),
    (3, 50)
;

;WITH SummedVals AS (
        SELECT  ID,
                SUM(value) / 30 Cnt
        FROM    Table1
        GROUP BY ID
)
, Vals AS (
        SELECT  ID,
                Cnt - 1 Cnt
        FROM    SummedVals
        UNION ALL
        SELECT  ID,
                Cnt - 1 Cnt
        FROM    Vals
        WHERE   Cnt > 0
)
SELECT  ID,
        NEWID()
FROM    Vals
ORDER BY 1

SQL Fiddle DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your help,your result is very correct,maybe i need time to understand it.
Try reading up about recursive common table expressions (CTE). That should help with the explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.