SQL产品矩阵

时间:2017-04-04 17:23:06

标签: sql sql-server tsql matrix

假设我卖T恤,我有一张桌子,我正在拉出售出的颜色和数量以及顾客,我想在x和y轴上创建一个100色的矩阵,所以我可以确定什么颜色客户购买他们的第一个订单以及他们在第二个订单上回购的颜色。

如果不在语句中写出1000个案例,我怎么能创建一个矩阵?

首次购买表

|Customer|Color|PurchaseQty|
----------------------------
|   1    |Blue |     2     |
|   2    |Red  |     1     |
|   3    |White|     2     |
---------------------------

第二次购买表

|Customer|Color|PurchaseQty|
----------------------------
|   1    |Red  |     1     |
|   2    |White|     3     |
|   3    |Blue |     1     |
---------------------------
       Red        White        Blue
--------------------------------------
Red  |              1
--------------------------------------
White|                           1
--------------------------------------
Blue |  1
--------------------------------------

Sample

2 个答案:

答案 0 :(得分:2)

Dynamic Pivots的许多例子,但这里是一个可以处理你的X / Y矩阵的例子

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(Color) From #Second  Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
Select [YAxis] as [Color],' + @SQL + '
From (
        Select YAxis = A.Color
              ,XAxis = B.Color
              ,Value = 1
         From  #First A
         Join  #Second B on (A.Customer=B.Customer)
     ) A
 Pivot (max(Value) For [XAxis] in (' + @SQL + ') ) p'
Exec(@SQL);

<强>返回

Color   Blue    Red     White
Blue    NULL    1       NULL
Red     NULL    NULL    1
White   1       NULL    NULL

答案 1 :(得分:1)

根据要求。我添加了一些记录来说明分发

示例数据优先

Customer    Color   PurchaseQty
1           Blue    2
3           White   2
2           Red     1
4           Red     1      -- < Added
5           Red     1      -- < Added

示例数据第二

Customer    Color   PurchaseQty
1           Red     1
3           Blue    1
2           White   3
4           Red     1      -- < Added
5           Blue    1      -- < Added

<强>查询

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(Color) From #Second  Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
Select [YAxis] as [Color],Y1Axis as [Customers],' + @SQL + '
From (
        Select YAxis = A.Color
              ,XAxis = B.Color
              ,Y1Axis= count(A.Customer) over (Partition By A.Color)
              ,Value = 1.0/count(*) over(Partition by A.Color)
         From  #First A
         Join  #Second B on (A.Customer=B.Customer)
     ) A
 Pivot (sum(Value) For [XAxis] in (' + @SQL + ') ) p'
Exec(@SQL);

退货 - 比较尺寸

enter image description here

适用于通用尺寸

只需将值设置为... ,Value = 1.0/count(*) over() ...

enter image description here