Access 2007:“SELECT COUNT(DISTINCT ......”)

问题描述 投票:1回答:4

我有一个包含StudyId,PatientId和StudyStartDateTime的表。我想在用户指定的两个日期之间绘制研究和患者的总数。问题在于计算不同的值。这是查询:

SELECT
    s.StudyStartDateTime,
    COUNT(s.StudyId),
    COUNT(s.PatientId)
FROM
    dbo_Study_ViewX211_Rpt AS s
WHERE
    s.StudyStartDateTime>=Forms![StudiesPatientsByDate]!txtStartDate,
    s.StudyStartDateTime<=Forms![StudiesPatientsByDate]!txtEndDate
GROUP BY s.StudyStartDateTime
ORDER BY s.StudyStartDateTime;

此查询几乎按预期工作,除了它计算具有相同StudyId或相同PatientId的行的重复项。我知道Access不支持COUNT(DISTINCT ...),但是我在解决这个问题上遇到了很多麻烦。任何帮助将非常感激。

sql database ms-access
4个回答
1
投票

您可以尝试使用子查询来计算计数,但是相关的子查询在性能方面往往会受到影响。

如果您愿意在两个查询而不是一个查询中执行此操作,这些将起作用:

SELECT
    s.StudyStartDateTime,
    COUNT(s.PatientId)
FROM
    dbo_Study_ViewX211_Rpt AS s
WHERE
    s.StudyStartDateTime>=Forms![StudiesPatientsByDate]!txtStartDate,
    s.StudyStartDateTime<=Forms![StudiesPatientsByDate]!txtEndDate
GROUP BY s.StudyStartDateTime, s.PatientId
ORDER BY s.StudyStartDateTime;


SELECT
    s.StudyStartDateTime,
    COUNT(s.StudyId),
FROM
    dbo_Study_ViewX211_Rpt AS s
WHERE
    s.StudyStartDateTime>=Forms![StudiesPatientsByDate]!txtStartDate,
    s.StudyStartDateTime<=Forms![StudiesPatientsByDate]!txtEndDate
GROUP BY s.StudyStartDateTime, s.StudyId
ORDER BY s.StudyStartDateTime;

请注意,我将计数字段添加到每个中的GROUP BY表达式中。

如果你想让它更“紧凑”,你可以为每个查询创建一个视图,并将它们连接到StudyStartDateTime上的一个独特查询,以便在一个结果集中获得结果。


1
投票

注意到dbo_前缀 - 这是否链接到SQL Server数据库?

如果是这样,您可以使用传递查询并使用COUNT(DISTINCT ...)语法,因为它将直接传递给SQL Server。


0
投票

将它放在一个单独的答案中,以便可以独立投票,但这篇博客文章讨论了使用子查询方法执行此操作:

Writing a Count(Distinct) Query in Access


0
投票

我已经采纳了JohnFx的建议,并且我已经创建了这两个子查询:

numStudiesByDate:

SELECT
    t.StudyStartDateTime,
    COUNT(s.StudyId) AS numStudies
FROM
    (SELECT DISTINCT
        StudyId
    FROM
        dbo_Study_ViewX211_Rpt
    GROUP BY StudyId) AS s
INNER JOIN
    dbo_Study_ViewX211_Rpt AS t
ON t.StudyId=s.StudyId
WHERE
    t.StudyStartDateTime>=Forms![StudiesPatientsByDate]!txtStartDate,
    t.StudyStartDateTime<=Forms![StudiesPatientsByDate]!txtEndDate
GROUP BY t.StudyStartDateTime
ORDER BY t.StudyStartDateTime;

numPatientsByDate:

SELECT
    t.StudyStartDateTime,
    COUNT(s.PatientId) AS numPatients
FROM
    (SELECT DISTINCT
        PatientId
    FROM
        dbo_Study_ViewX211_Rpt
    GROUP BY PatientId) AS s
INNER JOIN
    dbo_Study_ViewX211_Rpt AS t
ON t.PatientId=s.PatientId
WHERE
    t.StudyStartDateTime>=Forms![StudiesPatientsByDate]!txtStartDate,
    t.StudyStartDateTime<=Forms![StudiesPatientsByDate]!txtEndDate
GROUP BY t.StudyStartDateTime
ORDER BY t.StudyStartDateTime;

最后的查询:

numStudiesPatientsByDate:

SELECT
    s.StudyStartDateTime,
    s.numStudies,
    p.numPatients
FROM
    numStudiesByDate AS s
INNER JOIN
    numPatientsByDate AS p
ON
    s.StudyStartDateTime = p.StudyStartDateTime;

感谢所有的帮助,希望其他人觉得这很有用!

© www.soinside.com 2019 - 2024. All rights reserved.