Query table value aliasing in Oracle SQL
I have a homework assignment in SQL for Oracle 10g where I have to apply union to two different select statements, to return two columns. I need the values of each cell under vendor_state to indicate CA and every other value in ano开发者_Go百科ther state to return "Outside CA", to indicate they're elsewhere.
I applied the union and produced the two columns and the listings for CA, but many other state IDs were listed and I couldn't find an explanation for how to change the actual values in the query itself. Eventually, I stumbled on an answer, but I can't explain why this works. The code is as follows:
SELECT vendor_name,
vendor_state
FROM vendors
WHERE vendor_state IN 'CA'
UNION
SELECT vendor_name,
'Outside CA' AS vendor_state
FROM vendors
WHERE vendor_state NOT IN 'CA'
ORDER BY vendor_name
This gives me the exact answer I need, but I don't know why the aliasing in the second select statement can behave this way....no explanation is given in my textbook and nothing I've read indicates that column aliasing can be done like this. But, by switching the column name and the alias value, I have replaced the value being returned rather than the column name itself...I'm not complaining about the result, but it would help if I knew how I did it.
The trick is:
In the 1st SELECT, "vendor_state" is the value of the field itself, from the table. And, because of the WHERE clause, you will only have 'CA'
In the 2nd SELECT, "vendor_state" is NOT the value from the database field. Rather, its merely an alias for the literal value 'Outside CA'
Because both names match (as required by the UNION), your end result "looks like" all values came from same place, when in fact they didnt.
Maybe this will show better:
SELECT vendor_name, vendor_state, vendor_state AS vendor_state_new
FROM vendors
WHERE vendor_state IN 'CA'
UNION
SELECT vendor_name, vendor_state, 'Outside CA' AS vendor_state_new
FROM vendors
WHERE vendor_state NOT IN 'CA'
ORDER BY vendor_name
Now, for both queries, vendor_state
show the database value. And calculated_state
show the database value for the 1st SELECT, and the 'Outside CA' for the 2nd.
In your query, vendor_state
do the role of my vendor_state_new
: show database value for 1st, calculated value for 2nd. And the AS
is ommitted in 1st SELECT because vendor_state AS vendor_state
would be redundant (but it can be done for clarification purposes, and its a nice habit to do so when you mix calculated and "raw" values in a given colum name)
精彩评论