微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将三 (3) 个查询合并为一个

如何解决将三 (3) 个查询合并为一个

我想将这三个查询合并为一个查询

SELECT County,Result1,COUNT(Result1) AS Result1Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
GROUP BY County,Result1
ORDER BY County;

SELECT County,Result2,COUNT(Result2) AS Result2Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
  AND Result2 <> 'NULL'
GROUP BY County,Result2
ORDER BY County;

SELECT County,Result3,COUNT(Result3) AS Result3Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
  AND Result3 <> 'NULL'
GROUP BY County,Result3
ORDER BY County;

我希望输出如下所示:

County        Result         Totals
-----------------------------------    
Allegany      Car Services     2
Richmond      Car Services     3
Lynchberg     House Services   5
Charlotte     Car Services     12
Charlotte     House Services   2
northHampton  Car Serivces     6
northHampton  House Services   8

结果 1、2 和 3 是具有相同信息的下拉框。

解决方法

如果列总计代表 resulttotal 的国家明智的结果明智的总和,那么您的查询将是:

select Country,Result,sum(Result1Total) Totals
from (
    SELECT County,Result1 Result,Count(Result1) AS Result1Total
    FROM MainData
    WHERE (((Date) Between '01/01/2020' And '01/30/2020'))
    GROUP BY County,Result1


    union all

    SELECT County,Result2,Count(Result2) AS Result2Total
    FROM MainData
    WHERE (((Date) Between '01/01/2020' And '01/30/2020'))
    AND Result2 <> 'NULL'
    GROUP BY County,Result2

    union all

    SELECT County,Result3,Count(Result3) AS Result3Total
    FROM MainData
    WHERE (((Date) Between '01/01/2020' And '01/30/2020'))
    AND Result3 <> 'NULL'
    GROUP BY County,Result3
)
group by County,Result
ORDER BY County;
,

看起来 GROUPING SETS 在这里会派上用场:

SELECT
    County,ISNULL(ISNULL(Result1,Result2),Result3) AS Result,COUNT(Result1) AS Result1Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
GROUP BY GROUPING SETS (
    (County,Result1),(County,Result3)
)
ORDER BY County;

如果 Result 列可以为空,那么您需要一个更复杂的表达式:

    CASE WHEN GROUPING(Result1) = 0 THEN Result1
         WHEN GROUPING(Result1) = 0 THEN Result2
         ELSE Result3
    END AS Result,

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。