对于不满足WHERE子句的记录,如何获得值0?

时间:2015-03-18 19:48:26

标签: sql sql-server tsql

我在t-sql中有一个简单的SELECT语句:

SELECT Category, count(Category) as Total 
FROM mytable 
WHERE gender='F'
GROUP BY Category

哪个给了我

Category     Total
make up       10

这很好,但我也有Class_B类别。 Class_B仅由gender=M组成。所以,虽然没有Class_B并且我没有匹配任何记录,但我会像返回的表一样:

Category     Total
make up       10
shaving kit   0

任何建议都会受到赞赏。

编辑:主要更新,以使此更清晰。对不起。

4 个答案:

答案 0 :(得分:2)

从原始查询:

SELECT Category, count(Category) as Total 
FROM mytable 
GROUP BY Category

表中存在的所有类别都将被表示。您实际需要的是桌面上的join实际上包含您所有潜在类别。影响的事情:

SELECT c.category, count(m.*) as total
from categories c
left join myTable m on c.categoryId = m.categoryId
group by c.category

根据您的编辑,我有点不清楚......但这可能有效

select m.category, isnull(subQuery.total, 0)
  from mytable m
  left join (
    select category, count(1) as total
    from mytable
    where gender = 'f'
    group by category
    ) subQuery on m.category = subQuery.category
  group by m.category, subQuery.total

http://sqlfiddle.com/#!6/6b0a9/15

答案 1 :(得分:1)

这会有用吗?

; WITH FullCategory AS (
    SELECT DISTINCT Category
    FROM mytable
), FemaleCategoryCount AS (
    SELECT Category, count(Category) as Total 
    FROM mytable 
    WHERE gender='F'
    GROUP BY Category 
)
SELECT fc.Category, COALESCE(fcc.Total, 0) Total
FROM FullCategory fc
LEFT JOIN FemaleCategoryCount fcc
    ON fc.Category = fcc.Category

答案 2 :(得分:0)

如果您可以添加使行唯一的内容可能会起作用

SELECT t1.Category, count(distinct(t2.name)) as Total 
  FROM mytable t1 
  left join mytable t2  
    on t2.category = t1.category 
   and t2.gender='F'
 GROUP BY t1.Category

答案 3 :(得分:-1)

这是一种简单而有效的方法。

SELECT  Category, 
        SUM(CASE WHEN gender='F' THEN 1 ELSE 0 END) AS Total
FROM mytable 
GROUP BY Category