计算值的数量并将计数作为列返回

时间:2015-05-19 12:15:53

标签: sql ms-access

我试图编写一个查询,实际上,它结合了以下两个查询但我认为我有编写器阻止。我试过写一个子查询,但无济于事。我考虑过Cross Tab查询,但我还想避免任何特定于Access的内容。我试过UNION,但这似乎也没有用。我非常怀疑这只是我的垃圾。我很想尝试一个SQL PIVOT,但我以前没试过它们,从我今天的方式判断,我怀疑我会成功。

无论如何,适合我的查询是:

SELECT Operative.NAME, COUNT(*) AS [Yes to Left Tidy?]
FROM Operative INNER JOIN ([Survey Results] INNER JOIN JOBS ON [Survey Results].Job_Number = JOBS.Job_Number) ON Operative.USERID = JOBS.SCHEDULEITEMS_ASSIGNEDWORKERID
WHERE Q5 = 'yes'
GROUP BY Operative.NAME

SELECT Operative.NAME, COUNT(*) AS [No to Left Tidy?]
FROM Operative INNER JOIN ([Survey Results] INNER JOIN JOBS ON [Survey Results].Job_Number = JOBS.Job_Number) ON Operative.USERID = JOBS.SCHEDULEITEMS_ASSIGNEDWORKERID
WHERE Q5 = 'no'
GROUP BY Operative.NAME

如果您希望我详细说明桌子结构等,请告诉我。

3 个答案:

答案 0 :(得分:0)

你试过这个吗?

    select * FROM
    (SELECT Operative.NAME, COUNT(*) AS [Yes to Left Tidy?],'YES' AS Y/N
    FROM Operative INNER JOIN ([Survey Results] 
    INNER JOIN JOBS ON [Survey Results].Job_Number = JOBS.Job_Number) 
    ON Operative.USERID = JOBS.SCHEDULEITEMS_ASSIGNEDWORKERID
    WHERE Q5 = 'yes'
    GROUP BY Operative.NAME)A,
    UNION
    (SELECT Operative.NAME, COUNT(*) AS [Yes to Left Tidy?],'NO' AS Y/N
    FROM Operative INNER JOIN ([Survey Results] 
    INNER JOIN JOBS ON [Survey Results].Job_Number = JOBS.Job_Number) 
    ON Operative.USERID = JOBS.SCHEDULEITEMS_ASSIGNEDWORKERID
    WHERE Q5 = 'no'
    GROUP BY Operative.NAME)B

答案 1 :(得分:0)

好像你想按Q5分组,例如:

SELECT Operative.NAME, Q5 [Left Tidy?], COUNT(*)
FROM Operative INNER JOIN ([Survey Results] INNER JOIN JOBS ON [Survey Results].Job_Number = JOBS.Job_Number) ON Operative.USERID = JOBS.SCHEDULEITEMS_ASSIGNEDWORKERID
WHERE Q5 IN ('yes', 'no')
GROUP BY Q5, Operative.NAME

..如果你想要每行一对计数你可以得到这些结果并转动它们,例如:

SELECT * FROM (
SELECT Operative.NAME, Q5 [Left Tidy?], COUNT(*) c
FROM Operative INNER JOIN ([Survey Results] INNER JOIN JOBS ON [Survey Results].Job_Number = JOBS.Job_Number) ON Operative.USERID = JOBS.SCHEDULEITEMS_ASSIGNEDWORKERID
WHERE Q5 IN ('yes', 'no')
GROUP BY Q5, Operative.NAME) p
PIVOT (SUM(c) FOR [Left Tidy?] IN ([no], [yes])) x;

答案 2 :(得分:0)

在标准SQL中,这将是SUM(CASE WHEN Q5 = 'yes' THEN 1 ELSE 0 END),这只是根据条件对1或0求和。访问权限不支持CASE,但IIF应提供相同的结果:

SELECT Operative.NAME, 
   SUM(IIF(Q5 = 'yes', 1, 0)) AS [Yes to Left Tidy?],
   SUM(IIF(Q5 = 'no', 1, 0)) AS AS [No to Left Tidy?]
FROM Operative INNER JOIN ([Survey Results] INNER JOIN JOBS ON [Survey Results].Job_Number = JOBS.Job_Number) ON Operative.USERID = JOBS.SCHEDULEITEMS_ASSIGNEDWORKERID
WHERE Q5 IN ('yes', 'no') -- only needed if other values exist
GROUP BY Operative.NAME