我想计算不同绵羊的数量,我想把它放在一张桌子里。
像这样;Ewes | Rams | Lambs
8 | 5 | 12
我尝试的查询是这样的,但它不起作用;
SELECT COUNT(e.EweID) AS 'Ewe', COUNT(r.RamID) AS 'Ram', COUNT(l.LambID) AS 'Lamb'
FROM Sheep s
INNER JOIN Ewe e ON s.SheepID = e.EweID
INNER JOIN Ram r ON s.SheepID = r.RamID
INNER JOIN Lamb l ON s.SheepID = l.LambID
WHERE s.FarmerID = '123'
我不知道我做错了什么,这是我的数据库ERD;
答案 0 :(得分:3)
我认为你根本不需要FROM
:
select
(select count(*) from Ram where Famerid = 123) as RamCount,
(select count(*) from Ewe where Famerid = 123) as Count,
(select count(*) from Lamb where Famerid = 123) as LambCount
(您正在计算的行之间没有任何关系,请不要尝试创建一个。而是单独计算每个,将它们全部包装在外部选择中将所有内容保存在单个结果行中。)
答案 1 :(得分:1)
我认为这里的问题是你不需要内部联接而是外部联接...
SELECT COUNT(CASE WHEN e.EweID IN NOT NULL THEN e.EweID ELSE 0 END) AS 'Ewe', COUNT(r.RamID) AS 'Ram', COUNT(l.LambID) AS 'Lamb'
FROM Sheep s
LEFT OUTER JOIN Ewe e ON s.SheepID = e.EweID
LEFT OUTER JOIN Ram r ON s.SheepID = r.RamID
LEFT OUTER JOIN Lamb l ON s.SheepID = l.LambID
WHERE s.FarmerID = '123'
查看我在第一个计数(Ewe)中添加的案例陈述,以查看处理计数中空值的方法。
Left Outer Join逻辑运算符返回满足的每一行 第一个(顶部)输入与第二个(底部)输入的连接。它 还返回第一个输入中没有匹配行的任何行 在第二个输入。第二个输入中的不匹配行是 返回为空值。如果参数中不存在连接谓词 列,每行都是匹配的行。
答案 2 :(得分:0)
使用相关的子选择来进行计数:
SELECT (select COUNT(*) from Ewe e where s.SheepID = e.EweID) AS 'Ewe',
(select COUNT(*) from Ram r where s.SheepID = r.RamID) AS 'Ram',
(select COUNT(*) from Lamb l where s.SheepID = l.LambID) AS 'Lamb'
FROM Sheep s
WHERE s.FarmerID = '123'
您还可以简单地删除WHERE
子句以获取所有农场的数量。
答案 3 :(得分:0)
DECLARE @Count1 INT;
SELECT @Count1 = COUNT(*)
FROM dbo.Ewe;
DECLARE @Count2 INT;
SELECT @Count2 = COUNT(*)
FROM dbo.Ram;
DECLARE @Count3 INT;
SELECT @Count3 = COUNT(*)
FROM dbo.Lamb;
SELECT @Count1 AS 'Ewe' ,
@Count2 AS 'Ram' ,
@Count3 AS 'Lamb'