更改微软访问的cte

时间:2015-02-06 13:52:47

标签: sql ms-access syntax common-table-expression

我已经尝试过寻找答案但却找不到答案。

我有一个CTE,用于与数据库中的2个数据表相关的SQL查询。一个表的主键是另一个表中的外键,可以在第二个表中多次出现。我想计算每个外键出现在第二个表中的次数,并将其列为搜索结果中的总字段以及第一个表中的详细信息。由于CTE不能在Access中工作,我已将其调整为在联接中使用子选择,但在访问时仍然不喜欢它。

以下是表格的基本部分

CREATE TABLE [dbo].[Clients](
    [ClientRef] [int] NOT NULL,
    [Surname] [varchar](40) NULL,
    [Forenames] [varchar](50) NULL,
    [Title] [varchar](40) NULL,
 CONSTRAINT [CLIE_ClientRef_PK] PRIMARY KEY CLUSTERED 
(
    [ClientRef] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Policies](
    [PolicyRef] [int] NOT NULL,
    [ClientRef] [int] NULL,
 CONSTRAINT [POLI_PolicyRef_PK] PRIMARY KEY CLUSTERED 
(
    [PolicyRef] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

这是我的CTE

WITH CliPol (ClientRef, Plans) AS (SELECT ClientRef, COUNT(ClientRef) AS Plans FROM Policies GROUP BY ClientRef)
SELECT Clients.Surname, Clients.Forenames, Clients.Title, CliPol.Plans AS [No. of plans] 
FROM Clients LEFT JOIN CliPol ON Clients.ClientRef = CliPol.ClientRef 
ORDER BY Surname, Forenames;

这是我的调整后的查询。

SELECT Clients.ClientRef, Clients.Surname, Clients.Forenames, Clients.Title , Plans.NoPlans
FROM Clients
LEFT JOIN 
    (SELECT ClientRef, COUNT(ClientRef) AS NoPlans FROM Policies GROUP BY ClientRef) 
    AS Plans ON Plans.ClientRef = Clients.ClientRef
ORDER BY Clients.Surname, Clients.Forenames

不幸的是,当我尝试运行该查询时,Access会抛出错误#3131," FROM子句中的语法错误"

有人知道我如何在Access中使用它吗?

1 个答案:

答案 0 :(得分:1)

另一种方法是使用DCount()域聚合函数

SELECT 
    Clients.ClientRef, 
    Clients.Surname, 
    Clients.Forenames, 
    Clients.Title , 
    DCount("ClientRef", "Plans", "ClientRef=" & Clients.ClientRef) AS NoPlans
FROM Clients
ORDER BY Clients.Surname, Clients.Forenames