简单的max()函数和内部联接T-SQL

时间:2014-09-09 06:42:13

标签: sql sql-server tsql

我有简单的桌子让我感到困惑:

CREATE TABLE [dbo].[T3]
(
   [id] [int] IDENTITY(1,1) NOT NULL,
   [S_Id] [int] NULL,
   [P_Id] [int] NULL,
   [level] [int] NULL,
   [Path] [nvarchar](255) NULL
) ON [PRIMARY]

表中有数据

id  S_Id    P_Id    level   Path
------------------------------------
1   218252  218231  1   218231
2   218271  218252  1   218252
3   218271  218252  2   218231-218252

修改

我试着搞

ID, S_ID, P_ID, level, Path

Path的最大长度。

它应该返回id 3。

如果我试图从这样的路径获得max len:

select 
    b.id, a.p_id, a.s_id,
    max(len(a.path)) as Path, 
    a.path  
from 
    t3 a, t3 b
where 
    b.id = a.id
group by 
    a.p_id , a.s_id, b.id , a.path
order by 
    1

我获取所有数据,而不只是id为3的行,为什么?

3 个答案:

答案 0 :(得分:1)

如果您只想要最大路径记录......如果我错了,请纠正我。

;WITH tmp AS (select TOP 1 id from #TaskTask3 ORDER BY LEN(path) DESC)
select t.*
from #TaskTask3 t 
inner join tmp on tmp.id = t.id 

更新

;WITH tmp AS (select id, row_number() over (partition by S_Id, P_Id order by len(path) DESC) as rn from #TaskTask3)
select t.*
from #TaskTask3 t 
inner join tmp on tmp.id = t.id 
WHERE tmp.rn = 1

答案 1 :(得分:0)

我试图保持简单....还有其他方法(已经提到)但我认为你需要开始慢......:)

declare @maxLen int

select @maxLen =  max(len(path))
    from t3 

select * from t3 
where len (path) = @maxLen

答案 2 :(得分:0)

要以简单的方式提出weePee的答案,您可以使用以下查询:

select id,s_id,p_id,level  from t3 where len(path)= (select max(len(path)) from t3)

这是我用来创建和插入表t3的内容:

CREATE TABLE [dbo].[T3]
(
   [id] [int] IDENTITY(1,1) NOT NULL,
   [S_Id] [int] NULL,
   [P_Id] [int] NULL,
   [level] [int] NULL,
   [Path] [nvarchar](255) NULL
) ON [PRIMARY]
insert into t3 (s_id,p_id,level,path) values (218252,218231,1,'218231'),(218271,218252,1,'218252'),(218271,218252,2,'218231-218252')