日期:2014-05-17 浏览次数:20522 次
----------------------------
-- 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 行受影响)
*/