简体   繁体   中英

Create Table based on distinct attributes in SQL

I need to create a new table in MS Access based on a specific attribute. To simplify the problem, I will illustrate the desired result with a dummy table:

在此处输入图像描述

As you can see, I have different flowers (distinguished by their numbers - Flowerno), along with their attributes and values. The new table should be based on the distinct pairs of Attribute "color" and its Value. So in this example, we have two pairs: (color, red) and (color, yellow). Now, each pair belongs to a specific Flowerno and its other attributes like shape and fragrance. I would like to create a table with the attribute color as the main focus and present its other attributes of the same flower:

在此处输入图像描述

In other words, I want to list all colors along with the attributes and values distinctively in three different columns.

You need code that will do a lookup of color associated with flowerno and return that value for use in sorting/grouping. Could try calculating a field with DLookup:
GrpColor: DLookup("value", "table","attribute='color' AND flowerno=" & [flowerno])
Unfortunately, domain aggregate function can cause slow performance in query. Alternative would use subquery:

SELECT table.*, Q.GrpColor FROM table 
INNER JOIN (SELECT FlowerNo, [Value] AS GrpColor 
            FROM table WHERE attribute = "color") AS Q 
ON table.FlowerNo = Q.FlowerNo
WHERE Attribute<>"color";

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