开发者

Select average column value

I have a table containing order details. I would like to be able to select the average attribute for a certain item.

For example, select "item a", now find the average color of "item a". If there were 10 orde开发者_如何学Pythonrs of "item a" and the colors ordered broke down as follows:

4 - black

2 - blue

2 - red

1 - orange

1 - white

I would like for it to return "black". Is there any such statement that could do that?

Also, would it then be possible to weigh the average, for example giving the last 3 orders of "item a" a weight of 2, instead of 1. So if the last 3 orders were all yellow, it would essentially count as 6?


You can group by on color, and then select the first row:

select  color
from    OrderLines
where   ItemId = 'item a'
group by
        color
order by
        count(*) desc
limit   1

You could give some rows a higher weight with a subquery. This one gives the last 3 orders a higher weight:

select  color
from    (
        select  o1.color
        ,       case when
                (
                select  count(*)
                from    OrderLines o2
                where   o1.item = o2.item
                        and o1.OrderDt < o2.OrderDt
                ) < 3 then 2 else 1 end as weight
        from    OrderLines o1
        )
where   Item = 'item a'
group by
        color
order by
        sum(weight) desc
limit   1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜