SQL查询-将记录添加到所有类别

时间:2019-05-02 08:49:47

标签: sql sql-server

我有一张包含此数据的表:

ID       ENTRYID      ORDERID     NAME       VALUE
-----------------------------------------------------
1        123          1           Product    AAA
2        123          1           Product    BBB
3        123          2           Type       Consumer
4        123          3           Category   Device
5        123          4           Vendor     CompanyName

ENTRYID是用于标识相关行(条目组)的值。

我需要以下格式的数据:

Product        Name              Value
-------------------------------------------
AAA            Type              Consumer
AAA            Category          Device
AAA            Vendor            CompanyName
BBB            Type              Consumer
BBB            Category          Device
BBB            Vendor            CompanyName

因此,基本上从上述每个产品的条目组中,ORDERID = 1NAME = Product我需要添加其他详细信息。因此,在这种情况下,产品为AAA和BBB,并为每个产品添加类型,类别和供应商。每个具有相同ENTRYID的条目组可以有一个或多个产品。

我试图做这样的事情:

SELECT 
     CASE WHEN NAME = 'Product' THEN Value END AS PRODUCT,
     …
FROM MYTABLE

它在同一栏中为我提供了产品,但仅列出了两次

PRODUCT 
---------------
AAA
BBB

1 个答案:

答案 0 :(得分:1)

根据您的示例数据,我认为此查询将满足您的要求。它为给定的Product选择所有的ENTRYID值,然后JOIN将那些ENTRYID的值归为该SELECT P.VALUE AS Product, N.NAME AS Name, N.VALUE AS Value FROM (SELECT ENTRYID, VALUE FROM test WHERE NAME = 'Product') P JOIN (SELECT ENTRYID, NAME, VALUE FROM test WHERE NAME != 'Product') N ON N.ENTRYID = P.ENTRYID 的所有非产品值:

Product     Name        Value
AAA         Type        Consumer
AAA         Category    Device
AAA         Vendor      CompanyName
BBB         Type        Consumer
BBB         Category    Device
BBB         Vendor      CompanyName

输出:

--> DT_null --> Initial request -->
[]
--> DT0

1. Create initial structure:
Folder1/Folder2_copyme/file_to_copy.txt
Folder_move_to_me/

--> DT0 --> Initial request -->
`Folder1/`
`Folder2_copyme/`
`Folder_move_to_me/`
`Folder1/Folder2_copyme/file_to_copy.txt`
--> DT1

2. Copy `Folder2_copyme` to root folder
structure:
Folder1/Folder2_copyme/file_to_copy.txt
Folder2_copyme/file_to_copy.txt
Folder_move_to_me/


--> DT0 --> Request delta
`Folder1/`
`Folder2_copyme/`
`Folder_move_to_me/`
`Folder1/Folder2_copyme/file_to_copy.txt`
`Folder2_copyme/file_to_copy.txt`
--> DT2

3. Move `Folder2_copyme` from root folder to `Folder_move_to_me`
structure:
Folder1/Folder2_copyme/file_to_copy.txt
Folder_move_to_me/Folder2_copyme/file_to_copy.txt

--> DT0 --> Request delta
`Folder1/`
`Folder_move_to_me/`
`Folder1/Folder2_copyme/file_to_copy.txt`
`Folder_move_to_me/Folder2_copyme/`
?? where `Folder_move_to_me/Folder2_copyme/file_to_copy.txt` ???
--> DT3

Demo on dbfiddle