从具有1个不同列和Where条件的表中选择所有列

时间:2013-02-04 23:01:12

标签: sql

这已被多次询问,但我找不到适合我的解决方案。我有一个类似于下面的观点。我需要运行一个返回所有列的查询,但对于任何唯一的GLASS_ID只需运行一次。我还需要一个where子句 WHERE GLASS_ID LIKE'%'+ @PartialGlassId +'%'

VEH_ID   GLASS_ID   OPENING_SEQ  PART_NUM  PREFIX_CD ANT_FLAG  BLK_SIZE1
26975     DB00201        1          201       DB        Y        14.00
26864     DB00375        1          375       DB        N        16.00
26865     DB00375        1          375       DB        N        16.00
26866     DB00375        1          375       DB        N        16.00
38929     DB00408        1          408       DB        N        12.00
38930     DB00408        1          408       DB        N        12.00
38931     DB00408        1          408       DB        N        12.00
38932     DB00408        1          408       DB        N        12.00
38933     DB00408        1          408       DB        N        12.00
38990     DB00408        1          408       DB        N        12.00
38991     DW01015        1         1015       DB        N        12.00

结果应该是

VEH_ID  NAGS_GLASS_ID OPENING_SEQ PART_NUM PREFIX_CD ANT_FLAG BLK_SIZE1
26975     DB00201        1          201       DB        Y        14.00
26864     DB00375        1          375       DB        N        16.00
38929     DB00408        1          408       DB        N        12.00
对于WHERE GLASS_ID LIKE'%DB00%'

2 个答案:

答案 0 :(得分:1)

SELECT b.* 
FROM yourTable b
INNER JOIN
  (SELECT MIN(VEH_ID) as minV,  GLASS_ID as g
   FROM yourTable
   GROUP BY GLASS_ID) as d
  ON b.Glass_ID = d.g and b.VEH_ID = d.minV
WHERE b.GLASS_ID LIKE  '%DB00%'

注意:在这种情况下,WHERE子句也可以位于INNER JOIN的子查询中。

答案 1 :(得分:0)

Select distinct max(veh_ID), glass_ID, Opening_SEQ, part_Num, PRefix_CD, Ant_Flag, BLK_Size1
FROM yourTable
WHERE GLASS_ID LIKE '%' + @PartialGlassId + '%'
Group by glass_ID, Opening_SEQ, part_Num, PRefix_CD, Ant_Flag, BLK_Size1

其他选项

Select distinct group_Concat(veh_ID, ', '), glass_ID, Opening_SEQ, part_Num, PRefix_CD, Ant_Flag, BLK_Size1
FROM yourTable
WHERE GLASS_ID LIKE '%' + @PartialGlassId + '%'
Group by glass_ID, Opening_SEQ, part_Num, PRefix_CD, Ant_Flag, BLK_Size1