日期:2014-05-17  浏览次数:20406 次

MSSQL中将两列按先后显示在同一列(不是字符串的连接)
要求:有一个表Test,字段分别为ID(主键) name, need, had
现只需查询name、need、had ,并将 need 和 had 显示在同一列中,且同一个name必须显示在一起,对同一个name必须第一行显示其need 第二行显示其 had
举例
原表为:
ID name need had
-- ---- ---- ----
1  刘一 1000 900
2  陈二 2000 1680
3  张三  900 1440
4  李四 1800 2500
5  王五 1550 1350
6  赵六 1240 1000
7  孙七 1530 1530
8  周八  900 950
9  吴九 3570 3320
10 郑十 1730 2000
......

结果:
刘一 1000 
刘一 900
陈二 2000
陈二 1680
张三 900
张三 1440
李四 1800
李四 2500
......

目前存在的问题是:
sql语句:select name,数量 from (select ID, name,need as 数量 from test union all select ID, name,had from test) t order by ID
显示出来的结果中,某些name并不是都先显示need的数据,再显示had的数据,而是会反过来。
如下,刘一和陈二是先显示had的数据,再来显示need的数据。

刘一 900
刘一 1000
陈二 1680
陈二 2000
张三 900
张三 1440
李四 1800
李四 2500
......

------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-12-24 16:48:06
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go 
create table [test]([ID] int,[name] varchar(4),[need] int,[had] int)
insert [test]
select 1,'刘一',1000,900 union all
select 2,'陈二',2000,1680 union all
select 3,'张三',900,1440 union all
select 4,'李四',1800,2500 union all
select 5,'王五',1550,1350 union all
select 6,'赵六',1240,1000 union all
select 7,'孙七',1530,1530 union all
select 8,'周八',900,950 union all
select 9,'吴九',3570,3320 union all
select 10,'郑十',1730,2000
--------------开始查询--------------------------



select name,数量 from (select ID, name,