查询以运行每个实例。 MS-访问

时间:2013-07-09 14:06:50

标签: sql ms-access

我有一个MS-Access数据库,有两个表我想查询,基本表模式如下所示。我希望了解每个教区最早的教区教堂的细节 - 并且在这个例子中没有教堂里有'教区';我想拉出最早的教堂。

SITEDETAIL:

Site
Reference No. |  Civil Parish |  Site Name         |  NGR East  | NGR North   
1                Assynt          Old Parish Church    6137        3172
2                Assynt          St. Marys            6097        3870
3                Assynt          New Parish Church    6249        3490
4                Bower           Grimbister           2095        4067
5                Bower           St. Andrews          2304        3194
6                Halkirk         Firth Parish Church  7136        3450
7                Holm            Strath Parish Church 4586        2045
8                Holm            St Nicholas Parish   4132        3146    

SITEDATES:

Site 
Reference No.  | Date
1                1812
2                1300
3                1900
4                1760
5                1750
6                1838
7                1619
8                1774

我写了一个查询,提取'parish'的所有实例

SELECT SITEDETAIL.SITEREFNO, SITEDETAIL.CIVPARBUR_CDE, SITEDETAIL.SITENAME, SITEDETAIL.NGRE, SITEDETAIL.NGRN, SITEDATES.DATE

FROM SITEDETAIL INNER JOIN SITEDATES ON SITEDETAIL.SITEREFNO = SITEDATES.SITEREFNO
WHERE (((SITEDETAIL.SITENAME) Like "par*"));

但是,这并没有考虑名称中带有'par *'的多个/没有教堂的实例。

是否可以创建一个贯穿每个民事教区的SQL查询,并选择最早的'教区'或最早的教堂,或者是否有必要编写一个perl脚本来贯穿它们?这可能使用DBI吗?

期望的输出:

Site
Reference No. |  Civil Parish |  Site Name         |  NGR East  | NGR North   | Date
1                Assynt          Old Parish Church    6137        3172          1812
5                Bower           St. Andrews          2304        3194          1750
6                Halkirk         Firth Parish Church  7136        3450          1838
7                Holm            Strath Parish Church 4586        2045          1619

注意:在Assynt的情况下,'Old Parish Church'虽然年纪较大,但因为名字中有“教区”而被选中。

1 个答案:

答案 0 :(得分:1)

以下查询可以满足您的需求。它有点长,但它可以解决问题:

`select LIST.Civil_Parish, SD.Site_name, LIST.MSite_Date
from
(
select Civil_Parish, min(Site_date) as MSite_date
from SiteDetail
where Boolean = 1
group by Civil_Parish

union

select Civil_parish, min(Site_date) as MSite_date
from SiteDetail
where Civil_parish not in
(select Civil_parish
from SiteDetail
where Boolean = 1)
group by Civil_Parish) as LIST 
left join sitedetail SD on LIST.Civil_Parish = SD.Civil_Parish and LIST.MSite_Date = SD.Site_Date`

请注意以下事项:

1)我正在使用PowerUser的布尔建议。如果布尔列的值为1,则该行为Parish Church,如果不为,则为0。

2)为了本例的目的,我将表“SiteDates”和“SiteDetails”结合起来,因为它们是1比1。

查询的核心是A)在教区找到最古老的教区教堂,然后B)找到没有教区教堂的巴黎教堂。

A)的代码如下:

'select Civil_Parish, min(Site_date) as MSite_date
from SiteDetail
where Boolean = 1
group by Civil_Parish'

然后,我们与没有教区教堂的教区最古老的教堂联合起来:

'select Civil_parish, min(Site_date) as MSite_date
from SiteDetail
where Civil_parish not in
(select Civil_parish
from SiteDetail
where Boolean = 1)
group by Civil_Parish'

然后我们加入联合查询(这里名为“LIST”)和我们在教区和日期的原始“SITEDETAIL”表格,以引入教会名称。