Skip to content
Advertisement

how to solve this query using union

Display id and name for salesmen along with id and category of products in a single table. Indicate the source of the row in result by adding an additional column TYPE with possible values as ‘S’ (Salesman) and ‘P’ (Product). Display all rows.

I don’t how to add column “type” without using alter

select sid AS ID,sname from salesman
union
select category as "DETAILS" from product

actual tables are

Salesman Table

SID   SNAME    LOCATION
1     Peter    London
2     Michael  Paris
3     John     Mumbai
4     Harry    Chicago
5     Kevin    London
6     Alex     Chicago

Product Table

PRODID   PDESC           CATEGORY       DISCOUNT
101      Basketball      Sports         5
102      Shirt           Apparel        10
103      NULL            Electronics    15
104      CricketBat      Sports         20
105      Trouser         Apparel        5
106      Television      ELECTRONICS    20

expected output

TYPE  ID       DETAILS
P     101      Sports
P     102      Apparel
P     103      Electronics
P     104      Sports
P     105      Apparel
P     106      ELECTRONICS

Advertisement

Answer

You want result like this?

TYPE ID   DETAILS
S    1    Peter
S    2    Michael
S    3    John
S    4    Harry
S    5    Kevin
S    6    Alex
P    101  Sports
P    102  Apparel
P    103  Electronics
....

You can try query like this

select 'S' AS TYPE, sid AS ID,SNAME AS DETAILS from Salesman
union
select 'P' As TYPE, PRODID, category as "DETAILS" from Product
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement