我在SQL Server中有一个查询,我试图转换为MS-Access 2003中的查询。该查询旨在用作报告的基础。该报告有两个字段..'案例已分配'和'案例已关闭'。
SELECT
(SELECT COUNT(*)
FROM CaseDetail
WHERE CaseAssignedDate Between '1/1/2008' AND '1/1/2009') as 'Cases Assigned',
(SELECT COUNT(*)
FROM CaseDetail
WHERE CaseClosedDate BETWEEN '1/1/2008' AND '1/1/2009') as 'Cases Closed'
我在Access 2003中使用SQL时遇到了困难。为了Access,我已将'
字符替换为#
,但仍然没有乐趣。 Access是否在SELECT语句中出现SELECT问题?我从Access获得的错误不太有帮助。
Reserved error (-3205); there is no message for this error
此外,如果SQL语句需要从多个表中获取数据,该怎么办?例如......
SELECT
(SELECT COUNT(*)
FROM AssignedCases
WHERE CaseAssignedDate Between '1/1/2008' AND '1/1/2009') as 'Cases Assigned',
(SELECT COUNT(*)
FROM ClosedCases
WHERE CaseClosedDate BETWEEN '1/1/2008' AND '1/1/2009') as 'Cases Closed'
这在SQL中没有问题,但在Access中没有。
答案 0 :(得分:1)
我目前还没有可以测试的Windows机器,但这样的事情应该可行。
SELECT SUM(IIF(CaseAssignedDate
BETWEEN #1/1/2008# AND #1/1/2009#, 1, 0)) AS CasesAssigned,
SUM(IIF(CaseClosedDate
BETWEEN #1/1/2008# AND #1/1/2009#, 1, 0)) AS CasesClosed
FROM CaseDetail
根据我的经验,通常最好避免在Access中使用子查询。
编辑:
回应您的评论,我刚刚测试了Access允许这种替代方法:
SELECT *
FROM
(
SELECT 'CasesAssigned', COUNT(*) AS Total
FROM AssignedCases
WHERE CaseAssignedDate BETWEEN #1/1/2008# AND #1/1/2009#
UNION ALL
SELECT 'ClosedCases', COUNT(*) AS Total
FROM ClosedCases
WHERE CaseClosedDate BETWEEN #1/1/2008# AND #1/1/2009#
);
EDIT2:
如果您需要一行结果集,littlegreen's answer将会起作用。
答案 1 :(得分:1)
我不知道您收到此错误消息的位置,但您的问题是尝试执行Select语句而至少没有表或查询。你需要一些只有一条记录的'虚拟'表来实现这个目标。
SELECT
(SELECT COUNT(*)
FROM CaseDetail
WHERE CaseAssignedDate Between '1/1/2008' AND '1/1/2009'
) as 'Cases Assigned',
(SELECT COUNT(*)
FROM CaseDetail
WHERE CaseClosedDate BETWEEN '1/1/2008' AND '1/1/2009'
) as 'Cases Closed'
FROM DummyTableWithOneRecord;
答案 2 :(得分:1)
由于您的查询在SQL Server中有效,因此请创建一个使用该查询的Access传递查询(在SQL Server中)并将结果集返回给Access。
或者,根据该SELECT语句创建一个SQL Server视图,并链接到Access中的视图。
由于它已在SQL Server中运行,因此在Access中重新创建查询时看不到任何附加价值。
答案 3 :(得分:0)
3205错误是交叉表列标题太多。
这是您的查询解决方案:
SELECT 'Cases Asssigned' as Type, COUNT(*)
FROM CaseDetail
WHERE CaseAssignedDate Between '1/1/2008' AND '1/1/2009'
UNION
SELECT 'Cases Closed'as Type, COUNT(*)
FROM CaseDetail
WHERE CaseClosedDate BETWEEN '1/1/2008' AND '1/1/2009')
结果将分为两行而不是一行。
答案 4 :(得分:0)
在Access和SQL Server中都允许嵌套查询,但至少在SQL Server中,它要求您为嵌套查询设置虚拟别名,并且嵌套查询中的所有列都需要名称。这可能导致错误。
我建议跟随查询:
SELECT q1.CasesAssigned, q2.CasesClosed
FROM
(SELECT COUNT(*) AS CasesAssigned
FROM CaseDetail
WHERE CaseAssignedDate Between '1/1/2008' AND '1/1/2009') as q1,
(SELECT COUNT(*) AS CasesClosed
FROM CaseDetail
WHERE CaseClosedDate BETWEEN '1/1/2008' AND '1/1/2009') as q2