1

我有两张表 Business 和 BusinessCat。我需要一个 MSSQL 查询,它会得到以下结果:

ID | CategoryName | RecordCount
1  | Local        | 3
2  | National     | 1
3  | International| 2
4  | Other        | 0

我需要计算每个类别中有多少作为另一列。

业务表如下所示:

ID | Category | BusinessName
1  | 3        | Blackstone, Inc.
2  | 2        | Pet Smart
3  | 1        | John Doe
4  | 3        | Best Buy
5  | 1        | Sams Treats
6  | 1        | Eastcoast Tattoo

BusinessCat 表如下所示:

ID | CategoryName
1  | Local
2  | National
3  | International
4  | Other
4

6 回答 6

5
SELECT CN.ID, CN.CategoryName, ISNULL(Count(B.ID), 0) AS RecordCount
FROM Business B
RIGHT JOIN BusinessCat CN
ON B.Category = CN.ID
GROUP BY CN.ID, CN.CategoryName

或者

SELECT CN.ID, CN.CategoryName,
    (SELECT COUNT(*) FROM Business B WHERE B.Category = CN.ID) AS RecordCount
FROM BusinessCat CN

检查哪个查询更快。

于 2013-10-03T21:13:42.910 回答
0

好吧,弄错了,应该是(就像其他人所说的那样):

SELECT bc.id, bc.categoryname, COUNT(b.id)
  FROM businesscat bc LEFT JOIN business b ON (bc.id = b.category)
GROUP BY bc.id, bc.categoryname
;
于 2013-10-03T21:13:43.400 回答
0

你需要一个LEFT OUTER JOIN++ Group ByCount

SELECT bc.ID, bc.CategoryName, RecordCount = COUNT(b.ID)
FROM BusinessCat bc LEFT OUTER JOIN Business b
    ON bc.ID = b.Category
GROUP BY bc.ID, bc.CategoryName

Demonstration

于 2013-10-03T21:16:08.313 回答
0

你可以试试:

select bc.id, bc.cat_name, count(b.cat)
 from Business b (nolock)
inner join businesscat bc (nolock)
on b.cat=bc.id
group by bc.id, bc.cat_name
于 2013-10-03T21:18:02.197 回答
0

您需要一个左/右连接:

SELECT CN.ID, CN.CategoryName, isnull(Count(B.ID),0) RecCount
FROM Business B
RIGHT JOIN BusinessCat CN
              ON B.Category = CN.ID
GROUP BY CN.ID, CN.CategoryName
于 2013-10-03T21:24:55.153 回答
-1
select
      BC.ID,
      BC.CategoryName,
      coalesce( count(B.ID), 0 ) as RecordCount
   from
      BusinessCat BC
         LEFT JOIN Business B
            on BC.ID = B.Category
   group by
      BC.ID,
      BC.CategoryName
   ORDER BY
      BC.ID

您需要一个 LEFT-JOIN 到业务类别表,以允许一个没有记录的条目继续显示在最终列表中。

于 2013-10-03T21:15:28.577 回答