如何按唯一occ_code值筛选数据?寻求SQL替代Excel的高效方案
Absolutely switching to SQL for this makes total sense—Excel starts chugging with large datasets like 58k rows, but databases are built to handle this kind of operation efficiently.
Here's the straightforward SQL query that replicates exactly what you're doing in Excel:
SELECT * FROM projections ORDER BY occ_code ASC, indcode ASC;
How this works:
- The
ORDER BYclause first sorts all rows ascendingly byocc_code(just like your first Excel sort step). - For any rows that share the same
occ_code, it then sorts those subsets ascendingly byindcode—which matches your second grouping/sorting step. No need for explicit "grouping" here because we're just ordering, not aggregating data.
Pro tip for even better performance:
If you run this query often, adding a composite index on occ_code and indcode will make the sorting nearly instant, even as your dataset grows. Here's how to create it:
CREATE INDEX idx_projections_occ_ind ON projections (occ_code, indcode);
The database will use this index to skip the full-table sort entirely, pulling rows in the exact order you need directly from the index.
This will be way faster than Excel's manual sorting, and you can re-run it anytime your data updates without waiting for Excel to grind through the rows.
内容的提问来源于stack exchange,提问作者Calflamesfann

