计算SQL中的条目总数

时间:2014-01-06 20:06:55

标签: sql sql-server

我有三个数据表,只想显示该位置的位置和条目数。我正在努力创建一个sql语句来做到这一点。我正在使用MS SQL服务器。

下面我使用photoshop来展示我的三张桌子以及我如何尝试让最终输出看起来:

enter image description here

5 个答案:

答案 0 :(得分:2)

SELECT b.Name,count(n.employee)
FROM Branch b
LEFT JOIN Employee e ON e.branch=b.id
LEFT JOIN Entries n ON n.employee=e.name
GROUP BY b.Name

答案 1 :(得分:1)

测试数据

DECLARE @Employees TABLE (ID INT, Name NVARCHAR(100), BRANCH INT)
INSERT INTO @Employees
VALUES (1, 'jsmith', 4),(2, 'acook', 1),(3, 'jdoe', 4)

DECLARE @Branch TABLE (ID INT, NAME NVARCHAR(100))
INSERT INTO @Branch
VALUES (1, 'New York'), (2,'California'),(3,'Illinos'),(4,'Maine')

DECLARE @Entries TABLE (ID INT, Employee VARCHAR(100), [Date] DateTime)
INSERT INTO @Entries
VALUES (1, 'jsmith', '2014-01-01 20:05:00.000'),(2, 'jsmith', '2014-01-03 20:05:00.000'),
(3, 'jdoe', '2014-01-04 20:05:00.000'),(4, 'jsmith', '2014-01-04 20:05:00.000'),
(5, 'jdoe', '2014-01-03 20:05:00.000'),(6, 'acook', '2014-01-02 20:05:00.000')

<强>查询

SELECT B.NAME AS Location, ISNULL(Q.TotalEntries, 0) TotalEntries
FROM
(
SELECT B.NAME as Location, COUNT(*) TotalEntries
FROM @Entries EN INNER JOIN @Employees EM 
ON EM.name = EN.employee
INNER JOIN @Branch B 
ON EM.branch = B.id
GROUP BY b.name
) Q RIGHT JOIN @Branch B
ON Q.Location = B.NAME

结果集

╔════════════╦══════════════╗
║ Location   ║ TotalEntries ║
╠════════════╬══════════════╣
║ New York   ║            1 ║
║ California ║            0 ║
║ Illinos    ║            0 ║
║ Maine      ║            5 ║
╚════════════╩══════════════╝

答案 2 :(得分:0)

 SELECT B.Name AS [Location],
        COUNT(*)
 FROM Entries AS E
 JOIN Branch AS B
   ON B.Id = E.Id
 GROUP BY B.Name
 ORDER BY B.Name

答案 3 :(得分:0)

选择b.branch,count(*)来自分支b加入雇员e on e.branch = b.branch加入条目s on s.employee = e.name group by b.branch

答案 4 :(得分:0)

select b.name 'location', isnull(count(e.branch), 0) as count_total 
from branch b 
left join employee e on e.branch = b.id
left join entries en on en.employee = e.name
group by b.name