获取值的次数SQL Server

时间:2018-03-14 19:31:28

标签: sql-server

我正在试图找出如何编写一个SQL Server查询,该查询返回订单中项目一起出现的次数。这些表格如下:

ORDERS TABLE

Id    |    OrderId    |    Date
-----------------------------------
0001  |     589555    |    1/1/2018
0002  |     609510    |    1/1/2018

ORDERS ITEMS TABLE

Id    |    OrderId    |    ItemId
-----------------------------------
0001  |     589555    |    KP8
0002  |     589555    |    GH7
0003  |     589555    |    FR9
0004  |     609510    |    KP8
0005  |     609510    |    RFG
0006  |     609510    |    FR9
0007  |     609510    |    KP8

ITEMS TABLE

Id    |    ItemId
---------------------
1     |    KP8
2     |    RFG
3     |    FR9
4     |    GH7

我想要了解的是,与其他商品在同一订单上订购特定商品的次数如下:

KP8 | RFG | 10
KP8 | FR9 | 5
KP8 | GH7 | 2
RFG | KP8 | 10
RFG | FR9 | 7
RFG | GH7 | 1

etc, etc, etc

非常感谢任何帮助。提前谢谢......

运行SQL Server 2014

1 个答案:

答案 0 :(得分:2)

尝试以下。

DECLARE @Order TABLE(Id varchar(100),      OrderId   varchar(100),    ItemId varchar(100))
INSERT INTO @Order
VALUES
('0001'  ,     '589555'    ,    'KP8'),
('0002'  ,     '589555'    ,    'GH7'),
('0003'  ,     '589555'    ,    'FR9'),
('0004'  ,     '609510'    ,    'KP8'),
('0005'  ,     '609510'    ,    'RFG'),
('0006'  ,     '609510'    ,    'FR9'),
('0007'  ,     '609510'    ,    'KP8')


SELECT T1.ItemId Item1, T2.ItemId Item2, Count(*) AS Count FROM
(
   SELECT *, ROW_NUMBER() OVER(ORDER BY ItemId) R1 FROM @Order
) T1
INNER JOIN 
(
    SELECT *, ROW_NUMBER() OVER(ORDER BY ItemId) R2 FROM @Order
 )T2 ON  T1.OrderId=T2.OrderId AND T1.ItemId <> T2.ItemId AND R1> R2

GROUP BY T1.ItemId, T2.ItemId

<强>输出:

  Item1 Item2   Count
  GH7   FR9     1
  KP8   FR9     3 
  RFG   FR9     1
  KP8   GH7     1
  RFG   KP8     2

如果您想删除重复项(同一项目以同一顺序多次出现),您可以尝试以下内容。

SELECT  T1.ItemId Item1, T2.ItemId Item2, Count(*) AS Count FROM
(
 SELECT *, ROW_NUMBER() OVER(ORDER BY ItemId) R1
    FROM
      (
       SELECT DISTINCT ITEMID,ORDERID  FROM @Order 
      ) T
) T1
INNER JOIN 
(
    SELECT *, ROW_NUMBER() OVER(ORDER BY ItemId) R2 
    FROM
      (
       SELECT DISTINCT ITEMID,ORDERID  FROM @Order 
      ) T
 )T2 ON  T1.OrderId=T2.OrderId AND T1.ItemId <> T2.ItemId AND R1> R2

GROUP BY T1.ItemId, T2.ItemId

<强>输出

Item1   Item2   Count
GH7     FR9         1
KP8     FR9         2
RFG     FR9         1
KP8     GH7         1
RFG     KP8         1

工作样本rextester