2012-07-25 101 views
1

有人可以帮助我,我必须比较两个表,我的经理希望看到Access数据库中两个表之间的比较。两个表都包含IP电话,它们的类型,MAC和分配给它们的站点ID。我的经理想要的是以一种形式查看这些数据。我知道我可以用两个子表单来做到这一点,但是如果我可以用一个sql语句做到这一点会好得多,因为我知道它可以做到,但我只是愚蠢地做到这一点。我需要的是三列,列1 =手机类型,列2 =表1计数,列3 =表2计:查询MS-Access中的两个表格?

Handset Type |TABLE 1 COUNT| TABLE 2 COUNT| 
CISCO7911 | 100   | 50 
CISCO7942 | 100   | 50 

我目前只能查询一个有此其作品为列一二表,但我将如何添加最后一列,我已经尝试过UNION,但这会将数据添加到额外的行而不是另一列。

SELECT tbl_handsets.handset_type, 
    Count(IIf(handset_site_id='12345',1,Null)) AS myCompany_Number 
FROM tbl_Handsets 
GROUP BY tbl_handsets.handset_type 

任何想法?

回答

1

...

SELECT 
    handset_type, 
    Count(IIf(handset_site_id='12345',1,Null)) AS myCompany_Number 
FROM tbl_Handsets 
GROUP BY handset_type 

...并且用tbl_Accenture代替tbl_Handsets作为FROM返回你想要的Handset TypeTABLE 2 COUNT,然后建立一个查询将这两者作为子查询并将它们两者结合在一起。

SELECT 
    t1.handset_type, 
    t1.myCompany_Number AS [TABLE 1 COUNT], 
    t2.myCompany_Number AS [TABLE 2 COUNT] 
FROM 
    (
     SELECT 
      handset_type, 
      Count(IIf(handset_site_id='12345',1,Null)) 
       AS myCompany_Number 
     FROM tbl_Handsets 
     GROUP BY handset_type 
    ) AS t1 
    INNER JOIN 
    (
     SELECT 
      handset_type, 
      Count(IIf(handset_site_id='12345',1,Null)) 
       AS myCompany_Number 
     FROM tbl_Accenture 
     GROUP BY handset_type 
    ) AS t2 
    ON t1.handset_type = t2.handset_type 
+0

奇妙的你是我的英雄!!!! 非常感谢你,这正是我所需要的,很棒的工作! – 2012-07-25 13:35:40

+0

不客气,史蒂文。如果子查询对您不熟悉,请查看Allen Browne的页面:http://allenbrowne.com/subquery-01.html和http://allenbrowne.com/subquery-02.html – HansUp 2012-07-25 13:49:35

+0

谢谢我会看看这个,我通常只使用VBA,但最近我的任务是使用SQL – 2012-07-25 14:35:40

0

可能它可以帮助,但我测试它。

如果你的表有代表handset_type_id一列,然后如果你告诉我们该查询返回你想为Handset TypeTABLE 1 COUNT数据查询会变成

SELECT tbl_handsets.handset_type, 
    COUNT(*) AS Table1_Count, 
    (SELECT COUNT(*) FROM tbl_Accenture 
     WHERE tbl_Accenture.handset_type = tbl_handsets.handset_type 
     AND tbl_Accenture.handset_site_id = '15017') 
    AS Table2_Count 
FROM tbl_Handsets 
Where tbl_handsets.handset_site_id = '15017' 
GROUP BY tbl_handsets.handset_type 
+0

谢谢你,但它不工作..语法错误... – 2012-07-25 09:47:08

+0

检查更新,我错过了开“(”两个选择之前,试试吧。 – 2012-07-25 10:04:13

+0

嗨,现在的工作,但它不是给我我想要的结果,我需要由手机类型来划分的结果。 SELECT tbl_Handsets.handset_type, (SELECT COUNT(IIF(handset_site_id = '15017',1,NULL))FROM tbl_Handsets)AS Table1_Count, (SELECT COUNT(IIf(handset_site_id ='15017',1,Null))FROM tbl_Accenture)AS Table2_Count FROM tbl_Handsets GROUP BY tbl_handsets.handset_type – 2012-07-25 10:14:24