选择查询以检索公共数据

时间:2009-12-23 11:03:35

标签: sql

Model   Icolor

m1  i1

m1  i2

m1  i3

m2  i2

m2  i3

m2  i4

我有一个这样的表,我需要选择Icolor值,这对m1和m2都是常见的。

4 个答案:

答案 0 :(得分:1)

DECLARE @TABLE TABLE
(
    Model VARCHAR(30),
    LColour VARCHAR(30)
)

INSERT INTO @TABLE 
SELECT 'm1','i1' UNION
SELECT 'm1','i2' UNION
SELECT 'm1','i3' UNION
SELECT 'm2','i2' UNION
SELECT 'm2','i3' UNION
SELECT 'm2','i4' 

SELECT 
    LColour
FROM 
    @TABLE
GROUP BY 
    LColour
HAVING 
    COUNT(*) = (SELECT COUNT(DISTINCT Model) FROM @TABLE)

编辑以提供每种型号通用的所有颜色:)

答案 1 :(得分:0)

更新:

select color from 
  (select color, T2.num from test_table, 
     (select count(*) as num from (select distinct model from test_table) T) T2
group by color, T2.num
having count(*) = T2.num) T3

答案 2 :(得分:0)

我认为它应该是这样的:

SELECT tt.Icolor
FROM test_table tt
INNER JOIN test_table tt1 ON tt1.Icolor = tt.Icolor AND tt1.Model = 'm2'
WHERE tt.Model = 'm1'

答案 3 :(得分:-1)

select lcolor from Model where m1 = x
union 
select lcolor from Model where m2 = y

x是您的模型m1,y是您的模型m2值,或者如果它是一个数据类型,那么您在那里得到1。 union从两个查询的结果中获取共享值。我不确定语法是否正确(但我很确定它是)。如果没有,你可以谷歌。