表结构如下:
name num type
公司1 20 出境
公司1 12 进境
公司2 30 出境
公司2 32 进境
公司3 40 出境
公司3 45 进境
公司4 21 出境
公司4 19 进境
怎样让查询出来的结果,变成下面的样子呢
name num type
公司1 20 出境
公司1 20 进境
公司2 30 出境
公司2 30 进境
公司3 40 出境
公司3 40 进境
公司4 21 出境
公司4 21 进境
意思是说让同一公司的进境次数变得跟出境出数一样。
------解决方案--------------------
- SQL code
SELECT a.NAME,b.Num,a.Type FROM table1 AS aCROSS APPLY(SELECT TOP 1 num FROM table1 WHERE NAME=a.Name) AS b
------解决方案--------------------
- SQL code
create table tb(name varchar(10),num int,type varchar(10))insert into tb select '公司1',20,'出境'insert into tb select '公司1',12,'进境'insert into tb select '公司2',30,'出境'insert into tb select '公司2',32,'进境'insert into tb select '公司3',40,'出境'insert into tb select '公司3',45,'进境'insert into tb select '公司4',21,'出境'insert into tb select '公司4',19,'进境'go;with cte as(select *,row_number()over(partition by name order by (select 1))rn from tb)select name,(select num from cte where name=a.name and rn=1)num,type from cte a/*name num type---------- ----------- ----------公司1 20 出境公司1 20 进境公司2 30 出境公司2 30 进境公司3 40 出境公司3 40 进境公司4 21 出境公司4 21 进境(8 行受影响)*/godrop table tb
------解决方案--------------------
- SQL code
use Tempdbgo--> --> declare @T table([name] nvarchar(3),[num] int,[type] nvarchar(2))Insert @Tselect N'公司1',20,N'出境' union allselect N'公司1',12,N'进境' union allselect N'公司2',30,N'出境' union allselect N'公司2',32,N'进境' union allselect N'公司3',40,N'出境' union allselect N'公司3',45,N'进境' union allselect N'公司4',21,N'出境' union allselect N'公司4',19,N'进境' SELECT a.NAME,b.Num,a.Type FROM @T AS aCROSS APPLY(SELECT TOP 1 num FROM @T WHERE NAME=a.Name) AS b/*NAME Num Type公司1 20 出境公司1 20 进境公司2 30 出境公司2 30 进境公司3 40 出境公司3 40 进境公司4 21 出境公司4 21 进境*/
------解决方案--------------------
- SQL code
--SQL2000時use Tempdbgo--> --> declare @T table([name] nvarchar(3),[num] int,[type] nvarchar(2))Insert @Tselect N'公司1',20,N'出境' union allselect N'公司1',12,N'进境' union allselect N'公司2',30,N'出境' union allselect N'公司2',32,N'进境' union allselect N'公司3',40,N'出境' union allselect N'公司3',45,N'进境' union allselect N'公司4',21,N'出境' union allselect N'公司4',19,N'进境' SELECT a.NAME,Num=(SELECT TOP 1 Num FROM @T WHERE Name=a.Name),a.Type FROM @T AS a/*NAME Num Type公司1 20 出境公司1 20 进境公司2 30 出境公司2 30 进境公司3 40 出境公司3 40 进境公司4 21 出境公司4 21 进境*/
------解决方案--------------------
or:
- SQL code
create table tb(name varchar(10),num int,type varchar(10))insert into tb select '公司1',20,'出境'insert into tb select '公司1',12,'进境'insert into tb select '公司2',30,'出境'insert into tb select '公司2',32,'进境'insert into tb select '公司3',40,'出境'insert into tb select '公司3',45,'进境'insert into tb select '公司4',21,'出境'insert into tb select '公司4',19,'进境'goselect name,(select num from(select *,row_number()over(partition by name order by (select 1))rn from tb)t where name=a.name and rn=1)num,type from tb a/*name num type---------- ----------- ----------公司1 20 出境公司1 20 进境公司2 30 出境公司2 30 进境公司3 40 出境公司3 40 进境公司4 21 出境公司4 21 进境(8 行受影响)*/godrop table tb
------解决方案--------------------