我在SQL Server,客户,项目和事务处理中有3个表。表事务中的C_id和I.id是表“客户”和“项目”中的外键。我想要一个特定的日期范围,以查看所有客户的所有项目及其数量,无论有无交易。当物料尚未交易时,数量将为0。
客户(C)
id | Name
1 | C1
2 | C2
3 | C3
项目(一)
id | Name
1 | I1
2 | I2
3 | I3
4 | I4
交易次数
id | C_id | I_id | qty | date
1 | C1 | I1 | 10 | 2/2/2016
2 | C2 | I3 | 5 | 3/2/2016
3 | C1 | I2 | 3 | 3/2/2016
4 | C2 | I1 | 8 | 4/2/2016
5 | C1 | I1 | 2 | 5/2/2016
6 | C1 | I2 | 4 | 5/2/2016
7 | C2 | I1 | 2 | 6/2/2016
8 | C1 | I1 | 100 | 1/3/2016
9 | C2 | I2 | 200 | 2/3/2016
我想要2/2/2016和10/2/2016之间的数据范围的结果是:
C | I | qty
C1 | I1 | 12
C1 | I2 | 7
C1 | I3 | 0
C1 | I4 | 0
C2 | I1 | 10
C2 | I2 | 0
C2 | I3 | 5
C2 | I4 | 0
C3 | I1 | 0
C3 | I2 | 0
C3 | I3 | 0
C4 | I4 | 0
试试这个,希望对您有帮助。
select c.name,i.name,sum(isnull(t.qty,0))
from customers c
cross join Items I
left join transactions t on t.C_Id = C.Id and I.Id = t.I_Id and t.date between '2/2/2016' and '10/2/2016'
group by c.name,i.name
order by c.name,i.name
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句