简体   繁体   中英

How to query two fields (different) into one field

I'm new here. I've done a lot of searches and have had a lot of questions answered by existing posts. I think I'm getting to a point of real complication now, because I am not finding answers as easy anymore.

I'm going to explain my situation as bare/simplified as possible.

So I've got a Master Item Code Table :

item
E01
E02
E03
E04

And a Sub Item Code table that ties to the Master Item Code (this captures variations/sizes) It is a one to many relationship with the Master Item code:

item    subItem
E02     E02_S
E02     E02_M
E02     E02_L
E03     E03A
E03     E03B
E03     E03C
E04     E04A_S
E04     E04A_M
E04     E04B_L
E04     E04B_XL

Note that E01 does not have a subItem as it contains no variation.

I performed a query with join between the two tables to include all item and subitems:

SELECT master.item, [Size List].subItem
FROM master Left JOIN [Size List] ON master.[item] = [Size List].[item];

item    subItem
E01 
E02     E02_S
E02     E02_M
E02     E02_L
E03     E03A
E03     E03B
E03     E03C
E04     E04A_S
E04     E04A_M
E04     E04B_L
E04     E04B_XL

The list is as expected, with each subitem and master item occupying one row. Note that E02,E03 and E04 plain does not occupy a row when its subitems are available, and E01 occupies a row because no variation exists.

How would I update this query to merge the master and sub to one field so they would still occupy each row the way the join would? In general, I am trying to create a list of unique items, where the subitems act as unique replacing their related master level.

*combinedItemList

E01
E02_S
E02_M
E02_L
E03A
E03B
E03C
E04A_S
E04A_M
E04B_L
E04B_XL

Any help or insight would be most appreciated. Thank you!

The first statement gets all the items which doesn't have subitems.

The second statement gets all the sub items where item value exists and combines them.

select DISTINCT master.item
from master
left join [Size List]
master.[item] = [Size List].[item]
where [Size List].subItem is  null
UNION
SELECT DISTINCT [Size List].subitem
FROM    [Size List] 

Thank you! I edited the code you provided to the following, but I know what you were getting at! I had no idea a union could just merge two different fields that easily.

select DISTINCT master.item
from master 
left join [Size List] 
On master.[item] = [Size List].[item] 
Where [Size List].subItem is  null
Union
SELECT DISTINCT [Size List].subitem
FROM    [Size List] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM