【问题标题】:Select column values which are present 50% more with respect to other column values in sql选择相对于 sql 中的其他列值多出 50% 的列值
【发布时间】:2017-03-24 19:44:54
【问题描述】:

我需要编写一个 SQL 查询(SQL Server)。

我有一张看起来像这样的桌子。 表名:类

Subject Student Grade
Math      James   A
Math      John    B
Math      Eric    B
Physics   Crystal A  
Chemistry  James  C
Biology    John   A
Biology    Eric   B

等等……

我想显示包含所有列的表格,但在主题列中发现学生姓名的出现率为 50% 或更高

因此,例如,如果学生姓名 - “詹姆斯”出现在 4 个科目中的 2 个科目中,则应显示他的姓名,并应排除其他符合 50% 标准的人。

谢谢

【问题讨论】:

标签: c# sql sql-server


【解决方案1】:

使用有...

select Student
from Class
group by Student
having count(Student) >= (select count(distinct [Subject]) from Class) / 2.0

或者如果你喜欢变量...

declare @numOfSubjects int = (select count(distinct [Subject]) from Class)

select Student
from Class
group by Student
having count(Student) >= @numOfSubjects / 2.0

要恢复所有列,您可以将其包装在 CTE 中

with cte as(
    select Student
    from Class
    group by Student
    having count(Student) >= (select count(distinct [Subject]) from Class)) / 2.0)

select 
    c.*
from Class c
inner join cte on cte.Student = c.Student

【讨论】:

  • 你错过了 50% 的期限 :-)
  • 哈!好收获@GiorgosAltanis
  • 我想我还有一个 :-) 这里的整数除法不是有点危险吗?
  • 他说需要所有栏目而不仅仅是学生
  • 我不认为它会抛出,因为除法总是 .0 或 .5 但公平点
【解决方案2】:

只是为了获取所有列...

select *
from Class
where Student in (select Student
                    from Class
                   group by Student
                  having count(Student) >= (select count(distinct [Subject]) from Class) / 2.0)

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 2021-11-12
    • 2020-03-07
    • 2021-09-18
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多