基于条件的选择SQL查询

时间:2014-12-01 22:07:07

标签: sql sql-server sql-server-2008

例如我有一张桌子"信息"如下。

+--------+------------+------+------------+
| Entity | Department | Code | Code_count |
+--------+------------+------+------------+
| E1     | D1         |  123 |          5 |
| E1     | D1         |  234 |         10 |
| E1     | D1         |  345 |         20 |
| E1     | D2         |  456 |          2 |
| E1     | D2         |  567 |          5 |
| E1     | D2         |  678 |         10 |
+--------+------------+------+------------+ 

我的查询应该是这样的:对于每个EntityDepartment对,请选择code的{​​{1}}。

非常感谢任何帮助。感谢。

3 个答案:

答案 0 :(得分:0)

select t1.*
from your_table t1
join
(
  select entity, department, max(Code_count) as Code_count 
  from your_table
  group by entity, department
) t2 on t1.entity = t2.entity 
    and t1.department = t2.department 
    and t1.Code_count = t2.Code_count 

答案 1 :(得分:0)

这应该适合你:

SELECT ENTITY, DEPARTMENT, CODE
FROM TABLE
WHERE CODE_COUNT IN (
  SELECT MAX(CODE_COUNT) FROM TABLE GROUP BY ENTITY, DEPARTMENT)

SQL小提琴:http://sqlfiddle.com/#!2/482397/12

答案 2 :(得分:0)

使用Window Function获取结果。

SELECT Row_number()OVER(
                       partition BY Entity, Department
                       ORDER BY Code_count DESC) RN,
                   *
            FROM   table_name

partition BY将查询结果集划分为多个分区。 window函数分别应用于每个分区,并为每个分区重新开始计算。

SELECT Entity,
       Department,
       Code,
       Code_count
FROM   (SELECT Row_number()OVER(
                   partition BY Entity, Department
                   ORDER BY Code_count DESC) RN,
               *
        FROM   table_name) A
WHERE  rn = 1