计算多个列

时间:2016-11-01 13:58:07

标签: sql sql-server

我有一张这样的表:

+------------+---------------+-------------+
|store_number|entrance_number|camera_number|
+------------+---------------+-------------+
|          1 |             1 |           1 |
|          1 |             1 |           2 |
|          2 |             1 |           1 |
|          2 |             2 |           1 |
|          2 |             2 |           2 |
|          3 |             1 |           1 |
|          4 |             1 |           1 |
|          4 |             1 |           2 |
|          4 |             2 |           1 |
|          4 |             3 |           1 |
+------------+---------------+-------------+

总之,商店的编号为1及以上,每个商店的入口编号为1及以上,每个入口的编号为1及以上。

我想要做的是计算总共有多少个入口,以及每个商店总共有多少个摄像头。从上表生成此结果:

+------------+---------------+-------------+
|store_number|entrances      |cameras      |
+------------+---------------+-------------+
|          1 |             1 |           2 |
|          2 |             2 |           3 |
|          3 |             1 |           1 |
|          4 |             3 |           4 |
+------------+---------------+-------------+

如何依靠多列来产生此结果?

2 个答案:

答案 0 :(得分:10)

您可以使用每个项目的Object.keys(your_object)GROUP BY执行此操作:

COUNT()

从我的预期输出中可以看出,您正在查找出现的相机数量,同时还要查找Select Store_Number, Count(Distinct Entrance_Number) as Entrances, Count(Camera_Number) As Cameras From YourTable Group By Store_Number 个入口数量。

答案 1 :(得分:0)

这也可以,

DECLARE @store TABLE 
( store_number INT,entrance_number INT,camera_number INT)
INSERT INTO @store VALUES(1,1,1),(1,1,2),(2,1,1),(2,2,1),
(2,2,2),(3,1,1),(4,1,1),(4,1,2),(4,2,1),(4,3,1)

SELECT AA.s store_number, BB.e entrances,AA.c cameras FROM (

SELECT s,COUNT(DISTINCT c) c FROM ( SELECT store_number s, 
CONVERT(VARCHAR,store_number) + CONVERT(VARCHAR,entrance_number) + 
CONVERT(VARCHAR,camera_number) c FROM @store ) A GROUP BY s ) AA

LEFT JOIN

( SELECT s,COUNT(DISTINCT e) e FROM ( SELECT store_number s, 
CONVERT(VARCHAR,store_number) + CONVERT(VARCHAR,entrance_number) e
FROM @store ) B GROUP BY s ) BB ON AA.s = BB.s

希望它有所帮助。 :)