日期:2014-05-17 浏览次数:20776 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-05-22 14:31:49
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[UserCodes]
if object_id('[UserCodes]') is not null drop table [UserCodes]
go
create table [UserCodes]([Code] varchar(11),[Used] int)
insert [UserCodes]
select '668CT0A5M6P',1 union all
select '668MLOWTVCY',0 union all
select '668S9KNXU61',0 union all
select '868EMG6LXMP',1 union all
select '868LER010TP',0 union all
select '868M66JTULO',0 union all
select '868RS1H9K8V',1 union all
select '968K122UKXG',1 union all
select '968V1IAD0B7',1
--------------开始查询--------------------------
select LEFT([code],3) 号码段,COUNT(1)[号码段总数],SUM(CASE WHEN USED=0 THEN 1 ELSE 0 END )[未使用数量],
SUM(CASE WHEN USED=1 THEN 1 ELSE 0 END )[使用数量]
from [UserCodes]
GROUP BY LEFT([code],3)
----------------结果----------------------------
/*
号码段 号码段总数 未使用数量 使用数量
------ ----------- ----------- -----------
668 3 2 1
868 4 2 2
968 2 0 2
*/
with tb(a,b) as (
select '668CT0A5M6P', 1 union all
select '668MLOWTVCY', 0 union all
select '668S9KNXU61', 0 union all
select '868EMG6LXMP', 1 union all
select '868LER010TP', 0 union all
select '868M66JTULO', 0&n