P粉3024843662023-08-29 09:19:47
The SQL language has very strict requirements for knowing the number of columns in the result at query compile time, before any data is viewed. If you have to look at the data to determine the number of columns you want, then you can only use (potentially dangerous) dynamic SQL, which requires three steps:
In this case, you don't know how many columns are required, only that it is "up to 400 columns". With this in mind, you might see code like this:
SELECT ID, MAX(CASE WHEN IDX = 'a' THEN sell ELSE 0 END) as sell1, MAX(CASE WHEN IDX = 'b' THEN sell ELSE 0 END) as sell2, MAX(CASE WHEN IDX = 'c' THEN sell ELSE 0 END) as sell3, -- ... MAX(CASE WHEN IDX = '??' THEN sell ELSE 0 END) as sell400 FROM `buy_sell` GROUP BY ID
Yes, you do need to specify something in the query for every possible column. This also assumes that your sell
values are all greater than 0. If your values are likely to be a mix of positive and negative numbers, you might try using SUM()
instead of MAX()
.
This approach is also directly contrary to the set theory principles behind relational databases, so in practice you are better off letting client code or reporting tools do the pivoting on the data.