Database:
Transaction ProductID
1 1000
2 1000
2 1001
3 1000
3 1002
4 1000
4 1001
5 1003
In the above table, how to find this result with a T-SQL statement?
+-------------+-----------+-----------------+
| PRODUCTID1 | PRODUCTID2| SUPPORT |
+-------------+-----------+-----------------+
| 1000 | 1001 | 2 |
+-------------+-----------+-----------------+
| 1000 | 1002 | 1 |
+-------------+-----------+-----------------+
| 1000 | 1003 | 0 |
+-------------+-----------+-----------------+
| 1001 | 1002 | 0 开发者_Python百科 |
+-------------+-----------+-----------------+
| 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');
Thanks in advance.
Can you infer the zeros? i.e. can we just say that anything not listed is zero? if so:
select t1.PRODUCTID as [PRODUCTID1], t2.PRODUCTID as [PRODUCTID2],
COUNT(1) as [SUPPORT]
from transactions t1 inner join transactions t2
on t1.ORDERID = t2.ORDERID
and t1.PRODUCTID < t2.PRODUCTID
group by t1.PRODUCTID, t2.PRODUCTID
With output:
PRODUCTID1 PRODUCTID2 SUPPORT
----------- ----------- -----------
1000 1001 2
1000 1002 1
精彩评论