问题
I am trying to figure out how to select half the records where an ID is null. I want half because I am going to use that result set to update another ID field. Then I am going to update the rest with another value for that ID field.
So essentially I want to update half the records someFieldID with one number and the rest with another number splitting the update basically between two values for someFieldID the field I want to update.
回答1:
In oracle you can use the ROWNUM psuedocolumn. I believe in sql server you can use TOP. Example:
select TOP 50 PERCENT * from table
回答2:
You can select by percent:
SELECT TOP 50 PERCENT *fields* FROM YourTable WHERE ...
回答3:
update x set id=@value from (select top 50 percent * from table where id is null) x
回答4:
The following SQL will return the col_ids of the first half of the table.
SELECT col_id FROM table
WHERE rownum <= (SELECT count(col_id)/2 FROM table);
If the total number of col_ids is an odd number then you will get the first half - 1. This is because, for instance, we have 51 total records, the count(col_id)/2 returns 25.5, and since there is no rownum equal to this result, we get everything equal to 25 and below. That means the other 26 are not returned.
However, I have not seen the reverse statement working:
SELECT col_id FROM table
WHERE rownum > (SELECT count(col_id)/2 FROM table);
So if you want the other half of the table, you could just store the first results into a temp table, lets call it TABLE_A. Then just do MINUS on the original table from this table:
SELECT col_id FROM table
MINUSSELECT col_id FROM table_a
Hopefully this helps someone.
来源:https://stackoverflow.com/questions/686648/select-only-half-the-records