我不能按顺序排列一个值的最小值

时间:2017-03-30 17:59:01

标签: sql sql-server

我在sql server 2005中工作 我不知道如何获得返回的列的最小值。我尝试了不同的方法,但没有得到解决方案。感谢

select sum(c.duration) 
from song c , disc d, have e
where d.cod = e.cod AND e.can = c.cod 
group by d.name 

表:

song          have       disc
--------    -------   -----------
cod(int)     can(int)  cod
title        cod       name
duration               date

1 个答案:

答案 0 :(得分:0)

如果你只想要总和中的最小值,那么就可以进行简单的排序。

select top 1 sum(c.duration) as SumDuration
    from song c
    inner join have e on e.can = c.cod
    inner join disc d on d.cod = e.cod
    group by d.name
    order by SumDuration asc

如果要输出具有该最小值的所有求和记录,则使用CTE应该起作用

; with
    CTE as (
        select d.name, sum(c.duration) as SumDuration
            from song c
            inner join have e on e.can = c.cod
            inner join disc d on d.cod = e.cod
            group by d.name
    )
select name, SumDuration
    from CTE
    where SumDuration = (
        select min(SumDuration)
            from CTE
    )