简体   繁体   English

如何计算 SQL 服务器中带有 where 子句的行数?

[英]How do I count the rows with a where clause in SQL Server?

I am pretty much stuck with a problem I am facing with SQL Server.我几乎被 SQL 服务器所面临的问题所困扰。 I want to show in a query the amount of times that specific value occurs.我想在查询中显示特定值出现的次数。 This is pretty easy to do, but I want to take it a step further and I think the best way to explain on what I am trying to achieve is to explain it using images.这很容易做到,但我想更进一步,我认为解释我想要实现的最佳方法是使用图像来解释它。

I have two tables: Plant and Chest我有两张桌子: PlantChest

As you can see with the chest the column 'hoeveelheid' tells how full the chest is, 'vol' == 1 and 3/4 is == 0,75.正如您在胸部看到的那样,'hoeveelheid' 列表示胸部的饱满程度,'vol' == 1 和 3/4 == 0,75。 In the plant table there is a column 'Hoeveelheidperkist' which tells how much plants there can be in 1 chest.在植物表中有一列“Hoeveelheidperkist”,它说明了 1 个箱子里可以有多少植物。

select DISTINCT kist.Plantnaam, kist.Plantmaat, count(*) AS 'Amount'
from kist

group by kist.plantnaam, kist.Plantmaat

This query counts all the chests, but it does not seperate the count of 'Vol' chests and '3/4' chests.此查询计算所有箱子,但它不区分“Vol”箱子和“3/4”箱子的数量。 It only does This .它只做This What I want to achieve is this .我想要实现的是这个 But I have no idea how.但我不知道怎么做。 Any help would be much appreciated.任何帮助将非常感激。

If you use group by you don't need distinct如果你使用 group by 你不需要 distinct
and if you want the seprated count for hoeveelheid you ust add to the group by clause如果你想要 hoeveelheid 的单独计数,你可以添加到 group by 子句

    select DISTINCT kist.Plantnaam, kist.Plantmaat, kist.hoeveelheid, count(*) AS 'Amount'
    from kist
    group by kist.plantnaam, kist.Plantmaat, hoeveelheid

or if you want all the 3 count ond the samw rowx you could use a condition aggreagtion eg:或者,如果您想要所有 3 个 samw rowx 计数,您可以使用条件聚合,例如:

    select DISTINCT kist.Plantnaam, kist.Plantmaat
     , sum(case when kist.hoeveelheid ='Vol' then 1 else  0 end) vol 
     , sum(case when kist.hoeveelheid ='3/3' then 1 else  0 end) 3_4 
     , count(*) AS 'Amount'
    from kist
    group by kist.plantnaam, kist.Plantmaat

When you want to filter the data on the counts you have to use having clause.当您想过滤计数数据时,您必须使用having子句。 When ever you are using aggregate functions(sum, count, min, max) and you want to filter them on aggregation basis, use having clause当您使用聚合函数(sum、count、min、max)并且想要在聚合的基础上过滤它们时,请使用having子句

select DISTINCT kist.Plantnaam, kist.Plantmaat, count(*) AS 'Amount'
from kist

group by kist.plantnaam, kist.Plantmaat having count(*) = 1 -- or provide necessary conditions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM