有两张表
销售表
id 车架号 销售金额 销售时间 销售员
1 LVGB123 1980 2012-09-02 17:42:57.000 张三
2 LVGB545 2980 2012-09-12 11:42:57.000 李四
4 LVGB623 1980 2012-09-23 13:42:57.000 张三
5 LVGB532 2980 2012-09-25 14:42:57.000 王五
8 LVGB234 2980 2012-09-26 15:42:57.000 王五
10 LVGB623 1980 2012-09-27 13:42:57.000 李四
充值表
id 车架号 充值金额 充值时间 销售员 次数
1 LVGB123 1980 2012-09-06 17:42:57.000 张三
2 LVGB545 2980 2012-09-15 11:42:57.000 李四
4 LVGB623 1980 2012-09-26 13:42:57.000 张三
5 LVGB532 -2980 2012-09-27 14:42:57.000 王五
8 LVGB234 2980 2012-09-28 15:42:57.000 王五
10 LVGB623 1980 2012-09-28 13:42:57.000 王五
我想统计出一个销售员在2012-09-01 到2012-09-30 期间所销售出去或者充值的次数:
得出下表:
id 1980 2980 销售员 次数
1 4 0 张三 4
2 1 2 李四 3
3 1 2 王五 3
注意:1、销售表中的 5 LVGB532 2980 2012-09-25 14:42:57.000 王五 充值表中的5 LVGB532 -2980 2012-09-27 14:42:57.000 王五 记录意思是车架号为 LVGB532 在时间 2012-09-25 14:42:57.000购买 2980元的充值卡,又在时间2012-09-27 14:42:57.000退掉了这2980元的充值卡,相当于没有这次次数为零。也就是说这次王五没有业绩。
------解决方案--------------------
if object_id('[销售表]') is not null drop table [销售表]
go
create table [销售表] (id int,车架号 nvarchar(14),销售金额 int,销售时间 datetime,销售员 nvarchar(4))
insert into [销售表]
select 1,'LVGB123',1980,'2012-09-02 17:42:57.000','张三' union all
select 2,'LVGB545',2980,'2012-09-12 11:42:57.000','李四' union all
select 4,'LVGB623',1980,'2012-09-23 13:42:57.000','张三' union all
select 5,'LVGB532',2980,'2012-09-25 14:42:57.000','王五' union all
select 8,'LVGB234',2980,'2012-09-26 15:42:57.000','王五' union all
select 10,'LVGB623',1980,'2012-09-27 13:42:57.000','李四'
if object_id('[充值表]') is not null drop table [充值表]
go
create table [充值表] (id int,车架号 nvarchar(14),充值金额 int,充值时间 datetime,销售员 nvarchar(4),次数 sql_variant)
insert into [充值表]
select 1,'LVGB123',1980,'2012-09-06 17:42:57.000','张三',null union all
select 2,'LVGB545',2980,'2012-09-15 11:42:57.000','李四',null union all
select 4,'LVGB623',1980,'2012-09-26 13:42:57.000','张三',null union all
select 5,'LVGB532',-2980,'2012-09-27 14:42:57.000','王五',null union all
select 8,'LVGB234',2980,'2012-09-28 15:42:57.000','王五',null union all
select 10,'LVGB623',1980,'2012-09-28 13:42:57.000','王五',null
select * from [销售表]
select * from [充值表]
WITH TT
AS(
SELECT * FROM [销售表]
UNION ALL