2011-05-04 1 views
2

Base de données:règles d'association Rechercher dans SQL Server

Transaction ProductID 
1    1000 
2    1000 
2    1001 
3    1000 
3    1002 
4    1000 
4    1001 
5    1003 

et le tableau L1 (je continue à point Frequenties)

PRODUCTID SUPPORT 
    1000  4 
    1001  2 
    1002  1 
    1003  1 

Selon le tableau L1, comment trouver ce résultat avec une instruction T-SQL ? Et trouvez la valeur de support de ma table de transaction?

+-------------+-----------+-----------------+ 
| PRODUCTID1 | PRODUCTID2|  SUPPORT  | 
+-------------+-----------+-----------------+ 
|  1000 | 1001 |   2  | 
+-------------+-----------+-----------------+ 
|  1000 | 1002 |   1  | 
+-------------+-----------+-----------------+ 
|  1000 | 1003 |   0  | 
+-------------+-----------+-----------------+ 
|  1001 | 1002 |   0  | 
+-------------+-----------+-----------------+ 
|  1001 | 1003 |   0  | 
+-------------+-----------+-----------------+ 
|  1002 | 1003 |   0  |, 
+-------------+-----------+-----------------+ 

Table Test:

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) 
    SELECT PRODUCTID,COUNT(*) [SUPPORT] FROM transactions 
        GROUP BY PRODUCTID       
        ORDER BY PRODUCTID 

Merci à l'avance.

+0

Par quelle logique est la colonne de support produit? – Thomas

+0

Par exemple, pourquoi la ligne '(1000,1003)' n'a-t-elle pas une valeur de support de 1? – Thomas

+0

Qu'est-ce que cela tente d'accomplir? – Baaju

Répondre

1
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 
1
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 
Questions connexes