расчет среднего на основе условия - PullRequest
1 голос
/ 28 февраля 2020

Я пытаюсь составить формулу, которая дает мне среднюю сумму для заказа, если в заказе есть определенный элемент c, как я могу вычислить это?

Например, если таблица Похоже,

Order# | Item | Total for Entire order
a        Apple       50
a        Juice       50
a        Chicken     50
a        Bread       50
b        Bread       23
b        fish        23
c        Chicken     43
c        Wine        43
c        rice        43

Я хочу получить среднее значение всех заказов, в которых есть Цыпленок хотя бы один раз? но не хочу посчитать сумму одного заказа дважды в моем среднем расчете - спасибо за поиск

Ответы [ 2 ]

1 голос
/ 28 февраля 2020

Если есть новые формулы Dynami c Array:

=AVERAGE(INDEX(UNIQUE(FILTER(A2:C10,B2:B10="Chicken")),,3))

Если нет:

=SUMPRODUCT(((B2:B10="Chicken")*(C2:C10))/(COUNTIFS(A2:A10,A2:A10,B2:B10,"Chicken")+(B2:B10<>"Chicken")))/SUMPRODUCT((B2:B10="Chicken")/(COUNTIFS(A2:A10,A2:A10,B2:B10,"Chicken")+(B2:B10<>"Chicken")))

enter image description here

0 голосов
/ 28 февраля 2020

Если вы не против использования VBA, эта функция будет делать то, что вы хотите.

=Average_Orders_Subset(range, criteria)

Я изменил это в своем исходном ответе, чтобы улучшить функциональность, и добавил комментарии, чтобы Вы можете видеть, что он делает. С помощью функции вы можете добавить столько заказов, сколько хотите. Я также проверил его, и он будет работать, если буквы заказа будут заменены на числа, т.е. a = 1, b = 2 и т. Д. ... Надеюсь, это поможет. Не стесняйтесь спрашивать, если у вас есть какие-либо вопросы.

Если ваши данные начинаются в ячейке A1, они работают следующим образом: Пример: =Average_Orders_Subset(A1:C13,"Chicken")

enter image description here

С этой версией вы можете рассчитывать на курицу, рис, хлеб, что угодно. Если вы не знаете, , вот , как добавить код в рабочую книгу. Если хотите, я могу выслать вам копию рабочей книги с уже встроенной книгой.

Option Explicit

' User Defined Function to Average totals for only orders that contain specific string
' Pass the range and string you are looking for to the function
' Note the criteria string is case senstive so "chicken" is not the same as "Chicken"
'
' Example: =Average_Orders_Subset(A1:C13,"Chicken")
'
Public Function Average_Orders_Subset(rng As Range, criteria As String) As Double
Dim ws          As Worksheet
Dim arrData()   As Variant
Dim arrOrder()  As Variant
Dim i           As Long
Dim j           As Long
Dim cnt         As Long
Dim sum         As Double
Dim avg         As Double

    ' The worksheet with data
    Set ws = ThisWorkbook.ActiveSheet

    ' Counter and array to keep track of order letters
    cnt = 0
    ReDim arrOrder(cnt)


    With ws

        ' Create an array with all the values
        arrData = rng.Value2

        ' Iterate through the array looking for orders with the criteria e.g., "Chicken"
        For i = 2 To UBound(arrData)

            ' If criteria is found
            If arrData(i, 2) = criteria Then

                If cnt > 0 Then

                    ' If the array of order letters is less than 0
                    If arrData(i, 1) <> arrOrder(cnt - 1) Then

                        ' Checking if the order letter is already in the array so orders with two Chicken
                        ' or multipe of any criteria don't get double counted
                        ' Add them to the order letter array
                        arrOrder(cnt) = arrData(i, 1)
                        cnt = cnt + 1
                        ReDim Preserve arrOrder(cnt)

                    End If

                ElseIf cnt = 0 Then

                    ' This is to add the first occurence of the critera to the order array
                    arrOrder(cnt) = arrData(i, 1)
                    cnt = cnt + 1
                    ReDim Preserve arrOrder(cnt)

                End If

            End If

        Next i

        ' Remove the last empty value in the order array
        ' this is a result of the count expanding the array after the value is added
        ReDim Preserve arrOrder(UBound(arrOrder) - 1)

        ' Reset counter
        cnt = 0
        sum = 0

        ' For all the values in the order array
        For i = LBound(arrOrder) To UBound(arrOrder)

            ' For all the values in the range
            For j = 2 To UBound(arrData)

                ' If a row in the range matches the order letter add that value to the sum
                If arrData(j, 1) = arrOrder(i) Then
                    sum = sum + arrData(j, 3)
                    ' Keep track of the number of summed values for an average
                    cnt = cnt + 1
                End If

            Next j

        Next i

        ' Calculte the average
        avg = (sum / cnt)
        ' Pass the average back to the formula
        Average_Orders_Subset = avg

    End With

    Set rng = Nothing
    Set ws = Nothing

End Function
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...