查询以获得具有不同列值的结果

时间:2015-11-03 11:50:07

标签: sql sql-server tsql join group-by

我有一个像下面这样的SQL表:

Id  LId     ModuleId    CategoryId  Type    Name
1   abc1    1           10          c       arun
2   abc1    1           20          c       a!!run
3   abc1    1           30          c       a$$r@n
4   abc2    2           10          s       ketan
5   abc2    2           20          s       k!!etan
6   abc3    3           30          c       roha###n

我的表格中有一个categoryId列。并且有3个固定类别102030

我想得到的结果如下:

LIdType列和记录的分组必须包含不同的所有3个类别ID(102030)行。

结果应该是:

Id  LId     ModuleId    CategoryId  Type    Name
1   abc1    1           10          c       arun
2   abc1    1           20          c       a!!run
3   abc1    1           30          c       a$$r@n

2 个答案:

答案 0 :(得分:1)

如果正确理解你需要按照LId和Type制作组,之后检查如果CategoryId有3个值。在这种情况下,您可以在以下内容中使用COUNT() OVER()

<强> QUERY

select Id, LId, ModuleId, CategoryId, Type, Name  
from (
    select Id, LId, ModuleId, CategoryId, Type, Name 
           ,count(*) over (partition by LId, Type) cnt
    from #t
      ) t
where cnt = 3

示例数据

create table #t
(
    Id INT, 
    LId NVARCHAR(60), 
    ModuleId INT, 
    CategoryId INT, 
    Type NVARCHAR(60), 
    Name NVARCHAR(60) 
)
insert into #t values
(1,'abc1',1,10,'c','arun'),
(2,'abc1',1,20,'c','a!!run'),
(3,'abc1',1,30,'c','a$$r@n'),
(4,'abc2',2,10,'s','ketan'),
(5,'abc2',2,20,'s','k!!etan'),
(6,'abc3',3,30,'c','roha###n')

<强>输出

Id  LId     ModuleId    CategoryId  Type    Name
1   abc1    1           10          c       arun
2   abc1    1           20          c       a!!run
3   abc1    1           30          c       a$$r@n

<强>更新

如果同一组可以有CategoryId,例如:

Id  LId     ModuleId    CategoryId  Type    Name
1   abc1    1           10          c       arun
2   abc1    1           20          c       a!!run
3   abc1    1           20          c       a$$r@n
4   abc2    2           30          s       ketan
5   abc2    2           30          s       k!!etan
6   abc3    3           30          c       roha###n

你可以在下面这样做:

select Id, LId, ModuleId, CategoryId, Type, Name
from (
    select *, 
           count(*) over (partition by LId, Type) cnt2  
    from (
            select Id, LId, ModuleId, CategoryId, Type, Name 
                   , count(*) over (partition by LId, Type) cnt 
                   , count(*) over (partition by LId, Type,CategoryId) rnk     
            from #t
              ) t
    where cnt = 3 and rnk = 1
)x
where cnt2 = 3

使用上述解决方案仅返回所有3 CategoryId不同的组。

<强>样本

您可以在 SQL FIDDLE

进行测试

答案 1 :(得分:0)

我认为你需要的是:

select * from (
    select Id, LId, ModuleId, CategoryId, Type, Name 
    , ROW_NUMBER() over (Partition by CategoryId order by Id desc) numb
    from YourTableName
) temp
where numb = 1

这是我从你的问题中理解的。

相关问题