最小值和最大值的SQL查询

时间:2014-06-25 07:27:34

标签: sql sql-server

我在表格中有以下数据。每行中的值数可以变化,行数也可以变化。

该表有1列,带有csv格式的值。值始终为数字

Data
1,2
4
5,12, 10
6,7,8,9,10
15,17

我想最终得到一个带有以下

的临时表
Data           Lowest            Highest
1,2               1                  2
4                 4                  4
5,12, 10          5                  12
6,7,8,9,10        6                  10
15,17             15                 17 

任何人都可以帮助编写SQL查询或函数来实现这个

4 个答案:

答案 0 :(得分:2)

而不是功能,你可以通过这个来实现

 ;WITH tmp 
     AS (SELECT A.rn,split.a.value('.', 'VARCHAR(100)') AS String 
         FROM   (SELECT Row_number() OVER(ORDER BY (SELECT NULL)) AS RN, 
                        Cast ('<M>' + Replace([data], ',', '</M><M>') + '</M>' AS XML) AS String 
                 FROM   table1) AS A 
                CROSS apply string.nodes ('/M') AS Split(a)) 
SELECT X.data,Tmp.lower,Tmp.higher 
FROM   (SELECT rn,Min(Cast(string AS INT)) AS Lower,Max(Cast(string AS INT)) AS Higher 
        FROM   tmp 
        GROUP  BY rn) Tmp 
       JOIN (SELECT Row_number() OVER(ORDER BY (SELECT NULL)) AS RN1,data 
             FROM   table1) X 
         ON X.rn1 = Tmp.rn 

<强> FIDDLE DEMO

输出将是:


Data              Lower              Higher
1,2               1                  2
4                 4                  4
5,12, 10          5                  12
6,7,8,9,10        6                  10
15,17             15                 17 

答案 1 :(得分:1)

首先创建一个用户定义的函数,将'DATA'列的每一行转换为中间表:

/****** Object:  UserDefinedFunction [dbo].[CSVToTable]******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[CSVToTable] (@InStr VARCHAR(MAX))
RETURNS @TempTab TABLE
   (id int not null)
AS
BEGIN
    ;-- Ensure input ends with comma
    SET @InStr = REPLACE(@InStr + ',', ',,', ',')
    DECLARE @SP INT
DECLARE @VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', @INSTR ) <> 0 
BEGIN
   SELECT  @SP = PATINDEX('%,%',@INSTR)
   SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
   SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '')
   INSERT INTO @TempTab(id) VALUES (@VALUE)
END
    RETURN
END
GO

进一步解释功能here

然后使用Cross Apply我们可以得到所需的输出:

With CTE as
(
    select 
    T.Data, Min(udf.Id) as [Lowest],Max(udf.Id) as [Highest]
    from 
    Test T
    CROSS APPLY dbo.CSVToTable(T.Data) udf
    Group By Data
)
Select * from CTE 

Sample Code here...

Cross Apply的作用是:它将右表表达式应​​用于左表中的每一行,并生成具有统一结果集的结果表。

答案 2 :(得分:0)

Create table #temp1 (name varchar(100),value int )
Declare @len int
Select @len=(select max(LEN(name)-LEN(replace(name,',',''))) from table)
Declare @i int = 1 
while (@i<=@len+1)
begin
insert into #temp1
select name,PARSENAME(REPLACE(name,',','.'),@i) from table t 
set @i = @i+1

end

Select name,MIN(value) MINV,MAX(value) MAXV from #temp1 group by name

答案 3 :(得分:0)

declare @Testdata table (  Data varchar(max))
insert @Testdata select   '1,2'
insert @Testdata select   '4'
insert @Testdata select   '5,12, 10'
insert @Testdata select   '6,7,8,9,10'



;with tmp(  DataItem, Data, RN1) as (
select   LEFT(Data, CHARINDEX(',',Data+',')-1),
    STUFF(Data, 1, CHARINDEX(',',Data+','), ''),
    ROW_NUMBER()OVER(ORDER BY (SELECT NULL))AS RN1
from @Testdata
union all
select   LEFT(Data, CHARINDEX(',',Data+',')-1),
    STUFF(Data, 1, CHARINDEX(',',Data+','), ''),RN1
from tmp
where Data > ''
)

Select x.data,t.Low,t.Up FROM
 (Select RN1,MIN(Cast(DataItem AS INT)) As Low,
 MAX(Cast(DataItem AS INT)) As Up 
    FROM tmp t GROUP BY t.RN1)t
JOIN (Select ROW_NUMBER()OVER(ORDER BY (SELECT NULL))AS RN,data from @Testdata)X
ON X.RN = t.RN1