T-SQL - 查询非规范化表

时间:2017-01-17 23:32:19

标签: tsql

我有一个表'购买',其字段类似于此简化示例:

CustomerID  Item1   Price1   Item2   Price2   Item3   Price3  ... Item40  Price40
   111      15      26.00   23      5.00     31      2.75         36      17.50
   906      3        4.63   17       .77     18      3.74         19      22.60

项目/价格字段中的所有,部分或全部都可能包含值。 如果有物品,则会有价格。 始终在Item#order中输入项目。如果有3个项目,它们将位于前三个项目字段中......

我想将上表加入另一个表 - 客户 - 具有客户ID,姓名,地址,电子邮件......以便我可以获得购买了商品15,17,18和所有商品的所有客户的清单。 36.此时,我不想显示每个客户购买的所需物品。

我很感激任何建议。

1 个答案:

答案 0 :(得分:0)

另一个选项(动态性较差但性能较高),但您必须列出40个项目字段

Declare @YourTable table (CustomerID int,  Item1 int,   Price1 decimal(10,2),   Item2 int, Price2  decimal(10,2),   Item3 int, Price3  decimal(10,2), Item40 int, Price40  decimal(10,2))
Insert into @YourTable values 
(111,15,26.00,23,5.00,31,2.75,36,17.50),
(906, 3, 4.63,17, .77,18,3.74,19,22.60)

Select Distinct 
       A.CustomerID
 From  @YourTable A
 Cross Apply (Values (Item1)
                    ,(Item2)
                    ,(Item3)
                    -- ... Items 4 - 39
                    ,(Item40)
             ) B (value)

 Where B.Value in (15,17,18,36)
相关问题