2010-05-25 55 views
5

我必須從兩個sql語句的結果中選擇常見coloumns c1,c2,c3。需要結合兩條select語句的常見結果

1)

select c1, c2, c3,count(c3) from (select * from form_name 
where data_created >'1273446000' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>1 

2)

select c1, c2, c3,count(c3) from (select * from form_name 
where data_created>'1272236400' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>2 

,我需要選擇C1,C2,C3都相同,常見的查詢兩種結果發現。

這怎麼可能完成......任何人都可以幫忙嗎?

+0

你可以使用UNION來合併這兩個查詢到一個 – MUG4N 2010-05-25 14:17:41

回答

5

選擇列表中刪除count(c3),它可以不同(HAVING子句保證本)和OP只想比較C1,C2和C3。如果COUNT(c3)列不同,哪些行可以共用?沒有或有些,它會有所不同。也刪除派生表,它們不是必需的。因此,嘗試:

select 
    c1, c2, c3 
    from form_name 
    where data_created >'1273446000' and data_creazione<'1274569200' 
    group by c1,c2, c3 
    having count(c3)>1 
INTERSECT 
select 
    c1, c2, c3 
    from form_name 
    where data_created>'1272236400' and data_creazione<'1274569200' 
    group by c1,c2, c3 
    having count(c3)>2 
+0

是的,這是我想要的......謝謝KM – Anup 2010-05-25 17:03:43

0

您可以使用派生表,然後將它們連接在一起以獲得所需的結果。

select a.c1, a.c2, a.c3, a.acount, b.bcount 
From 
(select c1, c2, c3, count(*) as acount from (select * from form_name 
where data_created >'1273446000' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>1) a 
join 
(select c1, c2, c3, count(*) as bcount from (select * from form_name 
where data_created>'1272236400' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>2)b 
    on a.c1 = b.c1 and a.c2 = b.c2 and a.c3 = b.c3 
2

您是否試過用'UNION'加入2個查詢?

例如。

select c1, c2, c3,count(c3) from (select * from form_name 
where data_created >'1273446000' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>1  
union  
select c1, c2, c3,count(c3) from (select * from form_name 
where data_created>'1272236400' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>2 
+0

是的,我試過......但我想唯一的共同結果.....就像不同 – Anup 2010-05-25 14:26:28

+0

UNION給出了所有的行,OP只希望常見行 – 2010-05-25 14:34:29

2

我認爲INTERSECT將解決您的問題。更多信息here

select c1, c2, c3,count(c3) from (select * from form_name 
where data_created >'1273446000' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>1  
INTERSECT 
select c1, c2, c3,count(c3) from (select * from form_name 
where data_created>'1272236400' and data_creazione<'1274569200') 
group by c1,c2, c3 having count(c3)>2 
+0

INTERSECT給出了常見的行,但這個查詢不起作用,請參閱我的答案爲什麼。 – 2010-05-25 14:35:20