在sql中组合两行

时间:2016-01-29 18:33:09

标签: sql select

我很难搞清楚这一点。我有一个名为voeding的表和两行plantaardiginsecten的数据表。另请查看下面的图片来说明我的问题。

enter image description here

我应该使用哪个查询来找出最常用的voedingplantaardiginsecten)类型?

给予一些背景。用例是爬行动物最常食用哪种食物

2 个答案:

答案 0 :(得分:3)

使用GROUP BY之类的

select plantaardig, count(plantaardig) as count1
from voeding
group by plantaardig

如果你想混合,那么两者都使用UNION之类的

select * from (
select plantaardig as Foodee, count(plantaardig) as count1
from voeding
group by plantaardig

UNION

select insecten, count(insecten) 
from voeding
group by insecten ) xxx order by count1 desc;

答案 1 :(得分:0)

如果我理解正确,您想要查询返回最不安全的植物标记。

以下查询应该可以解决问题:

SELECT plantaardig
FROM Voeding
GROUP BY plantaardig
HAVING COUNT(*) >= ALL (SELECT COUNT(*)
                        FROM Voeding
                        GROUP BY plantaardig)

修改

要获得不安全感,您可以执行以下操作:

SELECT V.plantaardig, V.insecten
FROM Voeding AS V JOIN (SELECT plantaardig
                        FROM Voeding
                        GROUP BY plantaardig
                        HAVING COUNT(*) >= ALL (SELECT COUNT(*)
                                                FROM Voeding
                                                GROUP BY plantaardig)) AS t
     ON V.plantaardig = t.plantaardig