单个SQL查询中的多个计数

前端之家收集整理的这篇文章主要介绍了单个SQL查询中的多个计数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用以下代码获取4个特定部分中的文档数量
SELECT
    category.id,category.title,count(ts1.section_id) AS doc1,count(ts2.section_id) AS doc2,count(ts3.section_id) AS doc3,count(ts4.section_id) AS doc4
FROM
    category 
    LEFT JOIN category_link_section AS ts1
        ON (category.id = ts1.category_id AND ts1.section_id = 1)
    LEFT JOIN category_link_section AS ts2
        ON (category.id = ts2.category_id AND ts2.section_id = 2)
    LEFT JOIN category_link_section AS ts3
        ON (category.id = ts3.category_id AND ts3.section_id = 3)
    LEFT JOIN category_link_section AS ts4
        ON (category.id = ts4.category_id AND ts4.section_id = 4)
GROUP BY category.id,ts1.section_id,ts2.section_id,ts3.section_id,ts4.section_id

表’category’有一个id,标题
“category_link_section”表包含category_id,section_id和doc_id之间的id连接.@H_502_6@

如果任何列的计数为0,则在该列中显示0.但如果结果不是0,则显示所有截面结果的乘积结果.所以如果我的4个计数列应该返回:1,2,3;实际上会显示6,6,6;@H_502_6@

如果我为每个特定类别使用以下代码,我会得到我想要的结果:@H_502_6@

SELECT
    category.id,count(ts1.section_id) AS doc1
FROM
    category 
    LEFT JOIN category_link_section AS ts1
        ON (category.id = ts1.category_id AND ts1.section_id = 1)
GROUP BY category.id,ts1.section_id

但是我需要每次为每个部分循环浏览数据库.@H_502_6@

所以我的问题是,我需要依次调用每个部分,在sql之外构建我的表,还是可以在单个查询中完成?@H_502_6@

解决方法

@ VoteyDisciple的 answer在正确的轨道上,但他的查询需要一些改进:
SELECT c.id,c.title,SUM(ts1.section_id = 1) AS doc1,SUM(ts1.section_id = 2) AS doc2,SUM(ts1.section_id = 3) AS doc3,SUM(ts1.section_id = 4) AS doc4
FROM category AS c
  LEFT JOIN category_link_section AS ts1
    ON (c.id = ts1.category_id)
GROUP BY c.id;

说明:@H_502_6@

> IF()表达式是多余的,因为等式已经返回1或0.>从连接条件中取出ts1.section_id = 1,否则您将永远不会得到其他section_id值.>仅由c.id组成.我假设OP只需要每个类别一行,以及各个类别的每个section_id值的计数列.如果查询按c.id,ts1.section_id分组,那么每个类别最多可以有四行.>在选择列表中移动逗号.漂浮在线条开头的逗号看起来很丑陋.

猜你在找的MsSQL相关文章