DISTINCT with PARTITION BY vs. GROUPBY

后端 未结 3 1612
渐次进展
渐次进展 2021-02-01 10:33

I have found some SQL queries in an application I am examining like this:

SELECT DISTINCT
Company, Warehouse, Item,
SUM(quantity) OVER (PARTITION BY Company, War         


        
3条回答
  •  广开言路
    2021-02-01 11:19

    Although both queries seem to compute the same thing when you look at the columns, they are actually producing completely different set of rows.

    The first one using the analytical function will output exactly one row for each input row. That is for EACH stock information, it will return a row with the total quantity for the associated company/warehouse/item. (by the way computing the average would make more sense to me but who knows...)

    The second one will only return a single row for each company/warehouse/item combinaison.

    So yes, in that example the first query seems a bit useless... unless you want to compute some stock level statistic like the current stock ratio over the overall quantity by company/warehouse/item (just an example, don't know if it has any business meaning!)

    Analytical function are very powerful mechanism in SQL, in some sense way more powerful than a group-by. But use it with care... A simple rule of thumb could be: if you can compute it using a group-by, well, don't use an analytical function ;)

提交回复
热议问题