TSQL嵌套基本查询

时间:2013-08-06 13:41:27

标签: sql-server tsql subquery

我坚持使用T-SQL查询。我认为这是基本的。但我想不出来。有人可以善待它吗?提前谢谢!

这是我的问题。我想编写一个查询来执行以下任务:

原始数据:

Department Type Salary Age 
1 1 1000 30 
1 2 1500 31 
1 3 2000 25 
2 1 250 35 
2 2 50 20 
2 3 300 35

理想情况下,我想要一张表,其中包含以下信息:

Department Type Salary Age
1 3 2000 25
1 2 1500 31
1 1 1000 30
2 3 300 35
2 1 250 35

选择基于每个部门的比较。我比较每个部门内每种类型的薪水。并且将选择在同一部门中薪水大于或等于类型1的那些人。然后在每个部门内,记录按工资降序排列。

这是我的错误代码。

SELECT Department, Type, Salary, Age
FROM Database.dbo.Table1
WHERE Salary >=  
(
SELECT Salary
FROM Database.dbo.Table1
WHERE Type = 1
GROUP BY Department
)
GROUP BY Department

我希望插图清楚。如果不是,请随时告诉我。我可以解释一下。

再次感谢!

2 个答案:

答案 0 :(得分:1)

这里没有什么太棘手 - 只需要自我联接回到同一个表来识别Type = 1薪水,然后是一个相当正常的ORDER BY条款:

示例数据:

declare @t table (Department int,[Type] int, Salary int, Age int)
insert into @t(Department,[Type], Salary, Age ) values
(1 ,1 ,1000 ,30    ),
(1 ,2 ,1500 ,31    ),
(1 ,3 ,2000 ,25    ),
(2 ,1 ,250 ,35     ),
(2 ,2 ,50 ,20      ),
(2 ,3 ,300 ,35     )

查询:

select
    t1.*
from
    @t t1
        inner join
    @t t2
        on
            t1.Department = t2.Department and
            t1.Salary >= t2.Salary and
            t2.[Type] = 1
order by t1.Department, t1.Salary desc

您尝试使用GROUP BY错误,因为GROUP BY对最终输出订单没有任何影响 1


1 作为处理分组方式的副作用,输出可能按照对您有用的顺序排序 - 但这只是副作用而且不能保证。保证订购的唯一方法是使用ORDER BY

答案 1 :(得分:0)

select * from T as t1
where 
type=1
or
Exists(select 1 from t where t.[Department]=t1.[Department]
                             and
                             t.type=1
                             and 
                             salary<t1.salary 
                             )

order by [Department],salary DESC

SQLFiddle demo