表A (客户表)
ID,NAME(销售名), NUMBER
1, 'ZHANG', 1
2, 'LI' , 1
3, 'ZHANG' ,1
4, 'ZHANG' ,1
5, 'WANG' ,2
表B(合同表)
AID,NUM
2,1
3,2
效果如下:
name, 合同总数(A.ID=B.AID) 客户总数(A) 成单率
'ZHANG' 2 3 66.7%
'LI' 0 1 0
'WANG' 0 1 0
sql sql语句
------解决方案--------------------
你的例子是不是有错啊?
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-01-15 20:21:54
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86)
-- Jun 17 2011 00:57:23
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[表A]
if object_id('[表A]') is not null drop table [表A]
go
create table [表A]([ID] int,[NAME] varchar(5),[NUMBER] int)
insert [表A]
select 1,'ZHANG',1 union all
select 2,'LI',1 union all
select 3,'ZHANG',1 union all
select 4,'ZHANG',1 union all
select 5,'WANG',2
--> 测试数据:[表B]
if object_id('[表B]') is not null drop table [表B]
go
create table [表B]([AID] int,[NUM] int)
insert [表B]
select 2,1 union all
select 3,2
--------------开始查询--------------------------
select NAME,SUM(num) as [合同总数],COUNT(name) AS 客户总数,ISNULL(LEFT (CONVERT(VARCHAR(20),(SUM(num)*1./COUNT(name))),4),0)+'%' 成单率
from [表A] a LEFT JOIN [表B] b ON a.id=b.aid
GROUP BY name
----------------结果----------------------------
/*
NAME 合同总数 客户总数 成单率
----- ----------- ----------- ---------
LI 1 1 1.00%
WANG NULL 1 0%
ZHANG 2 3 0.66%
警告: 聚合或其他 SET 操作消除了 Null 值。
(3 行受影响)
*/
------解决方案--------------------