Find association rules in SQL Server
Database:
Transaction ProductID
1 1000
2 1000
2 1001
3 1000
3 1002
4 1000
4 1001
5 1003
and L1 table (i keep Frequenties item)
PRODUCTID SUPPORT
1000 4
1001 2
1002 1
1003 1
According to L1 table, how to find this result with a T-SQL statement? And find support value from my Transaction table?
+-------------+-----------+-----------------+
| PRODUCTID1 | PRODUCTID2| SUPPORT |
+-------------+-----------+-----------------+
| 1000 | 1001 | 2 |
+-------------+-----------+-----------------+
| 1000 | 1002 | 1 |
+-------------+-----------+-----------------+
| 1000 | 1003 | 0 |
+-------------+-----------+-----------------+
| 1001 | 1002 | 0 |
+-------------+-----------+-----------------+
| 1001 | 1003 | 0 |
+-------------+-----------+-----------------+
| 1002 | 1003 | 0 |,
+-------------+-----------+-----------------+
Test Table:
create table transactions(
ORDERID INT,
PRODUCTID INT
);
insert into transactions(ORDERID, PRODUCTID)
values ('1', '1000')
,('2', '1000')
,('2', '1001')
,('3', '1000')
,('3', '1002')
,('4', '1000')
,('4', '1001'),
('5', '1003');
CREATE TABLE L1
(PRODUCTID INT,
SUPPORT INT )
INSERT INTO L1 (PRODUCTID,SUPPORT)
开发者_JAVA百科 SELECT PRODUCTID,COUNT(*) [SUPPORT] FROM transactions
GROUP BY PRODUCTID
ORDER BY PRODUCTID
Thanks in advance.
WITH Pairs
As (SELECT A.PRODUCTID AS PRODUCTID1,
B.PRODUCTID AS PRODUCTID2
FROM L1 A
JOIN L1 B
ON A.PRODUCTID < B.PRODUCTID)
SELECT PRODUCTID1,
PRODUCTID2,
COUNT(t2.ORDERID) AS SUPPORT
FROM Pairs
LEFT JOIN transactions t1
ON t1.PRODUCTID = PRODUCTID1
LEFT JOIN transactions t2
ON t2.PRODUCTID = PRODUCTID2
AND t1.ORDERID = t2.ORDERID
GROUP BY PRODUCTID1,
PRODUCTID2
Select Product1.ProductId, Product2.ProductId, Count( T.OrderId ) As Support
From L1 As Product1
Join L1 As Product2
On Product2.ProductId > Product1.ProductId
Left Join (
Select T1.OrderId, T1.ProductId As Product1, T2.ProductId As Product2
From Transactions As T1
Join Transactions As T2
On T2.OrderId = T1.OrderId
And T2.ProductId > T1.ProductId
) As T
On T.Product1 = Product1.ProductId
And T.Product2 = Product2.ProductId
Group BY Product1.ProductId, Product2.ProductId
精彩评论