SQL:用一切加入一切

时间:2013-12-17 11:29:59

标签: sql sql-server

我有一个rabatt数据库(销售折扣),我想要一个返回的SQL语句:

   fnrvon     fnran      prozent
----------- ----------- -----------
101             102        5.25
101             103        15.75
101             104        0.00
101             105        0.00
101             106        0.00
101             107        0.00
102             101        5.50
102             103        10.50
102             104        0.00
102             105        0.00
102             106        0.00
102             107        0.00
........

我试过

select * from rabatt r1 cross join rabatt r2;

select distinct r1.fnrvon, r2.fnran 
    from rabatt r1 
    cross join rabatt r2
    where r1.fnrvon != r2.fnran
    order by r1.fnrvon;

但不知何故它不会返回上述结果。有什么想法吗?

SQLFiddle

上的示例

1 个答案:

答案 0 :(得分:2)

如果您可以访问firma表:

,这应该可行
SELECT f1.fnr AS 'from', f2.fnr AS 'to', COALESCE(r.prozent, 0)
FROM firma f1
CROSS JOIN firma f2
LEFT JOIN rabatt r ON r.fnrvon = f1.fnr AND r.fnran = f2.fnr
WHERE f1.fnr != f2.fnr
ORDER BY f1.fnr, f2.fnr;

如果由于某种原因你不能用子查询替换firma

SELECT fnrvon FROM rabatt UNION SELECT fnran FROM rabatt;