日期:2014-05-16 浏览次数:20554 次
----------------------------------------------------------------
-- Author :DBA_HuangZJ(发粪涂墙)
-- Date :2014-04-10 11:20:33
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)
-- Apr 2 2010 15:48:46
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[Member]
if object_id('[Member]') is not null drop table [Member]
go
create table [Member]([Id] int,[Name] nvarchar(4),[Sex] nvarchar(2),[Marital] nvarchar(4),[OrgId] int)
insert [Member]
select 1,N'张一',N'男',N'未婚',3 union all
select 2,N'张二',N'男',N'已婚',2 union all
select 3,N'张三',N'女',N'未知',1 union all
select 4,N'张四',N'女',N'未婚',2 union all
select 5,N'张五',N'男',N'已婚',1 union all
select 6,N'张六',N'男',N'未知',3
--> 测试数据[ORG]
if object_id('[ORG]') is not null drop table [ORG]
go
create table [ORG]([Id] int,[Name] nvarchar(6))
insert [ORG]
select 1,N'后勤部' union all
select 2,N'外联部' union all
select 3,N'财务部'
--------------生成数据--------------------------
;WITH YM AS (
select A.*,B.NAME ORGNAME from [Member] A LEFT JOIN ORG B ON A.ORGID=B.ID)
SELECT ORGNAME,COUNT(1)人数,COUNT(CASE WHEN SEX=N'男' THEN 1 ELSE NULL END )N'男',
COUNT(CASE WHEN SEX=N'女' THEN 1 ELSE NULL END )N'女',
COUNT(CASE WHEN Marital=N'未婚' THEN 1 ELSE NULL END )N'未婚',
COUNT(CASE WHEN Marital=N'已婚' THEN 1 ELSE NULL END )N'已婚'
,
COUNT(CASE WHEN Marital=N'未知' THEN 1 ELSE NULL END )N'未知'
FROM YM
GROUP BY ORGNAME
----------------结果----------------------------
/*
ORGNAME 人数 男 女 未婚 已婚 未知
------- ----------- ----------- ----------- ----------- ----------- -----------
后勤部 2 1 1 0 1 1
外联部