title: Median instead avg() in SQL Server 2012
body: <p>I have this query  </p>
  
  <pre><code>;WITH cte AS
  (
      SELECT
          *,
          DATEPART(WEEKDAY, Dt) AS WeekDay,
          PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY SaleCount) OVER (PARTITION BY CustomerType, [CustomerName], ItemRelation, DocumentNum, DocumentYear) AS PERCENTILE,
          AVG(SaleCount) OVER (PARTITION BY CustomerType, [CustomerName], ItemRelation, DocumentNum, DocumentYear, DATEPART(WEEKDAY, Dt), IsPromo) AS AVG_WeekDay
      FROM
          promo_data_copy
  )
  UPDATE a 
  SET SaleCount = cte.AVG_WeekDay
  FROM CTE
  JOIN promo_data_copy a ON a.Dt = cte.dt
                         AND a.ItemRelation = cte.ItemRelation 
                         AND a.CustomerName = cte.CustomerName
                         AND a.DocumentNum = cte.DocumentNum 
                         AND a.DocumentYear = cte.DocumentYear 
                         AND a.CustomerType = cte.CustomerType 
                         AND a.ispromo = cte.ispromo
  WHERE 
      CTE.PERCENTILE &lt; CTE.SaleCount
      AND DATEPART(WEEKDAY, CTE.Dt) &lt; 7
      AND CTE.ispromo = 0 ;
  </code></pre>
  
  <p>Here there is string</p>
  
  <pre><code>avg(SaleCount) over (Partition by CustomerType, [CustomerName], ItemRelation, DocumentNum, DocumentYear,datePart(WEEKDAY,Dt), IsPromo) as AVG_WeekDay
      From promo_data_copy)
  </code></pre>
  
  <p>How can I calculate the median instead of <code>avg()</code>? This query replaces outliers by mean value.</p>
  
  <p>I need replace it by median, so the string above must be instead of <code>avg()</code>.</p>
  
  <p>Contain median (but there is no median function in T-SQL like in Excel)</p>
  
  <p>Can anybody help please?</p>