开发者

Select query for retrieving common data

开发者 https://www.devze.com 2022-12-15 04:12 出处:网络
ModelIcolor m1i1 m1i2 m1i3 m2i2 m2i3 m2i4 I am having a table like this, i need to select Icolor values which is co开发者_StackOverflow社区mmon to both model m1 and m2.DECLARE @TABLE TABLE
Model   Icolor

m1  i1

m1  i2

m1  i3

m2  i2

m2  i3

m2  i4

I am having a table like this, i need to select Icolor values which is co开发者_StackOverflow社区mmon to both model m1 and m2.


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)

Edited to give all colours that are common to every model :)


I beleive it shuld be something like this:

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'


UPDATED:

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


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

x is your model m1 and y is your model m2 value or if it is a bit datatype then you've got a 1 there. union gets you the shared values from the results of both queries. I'm not sure if the syntax is correct (but I'm pretty sure it is). If not you can google it.

0

精彩评论

暂无评论...
验证码 换一张
取 消