Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Median with Union

Posted on 2014-02-22
2
Medium Priority
?
207 Views
Last Modified: 2014-02-24
Experts,
I have a query that looks like the code below.
I would like to calculate the Median of Price in addition to the Max, Min and Avg.
How would I go about doing that with a query of this form?

Thanks in advance.

SELECT          a.productid
            , Count(a.productID) as Cnnt
            , Max(a.Price) as 'MaxPrice'
            , MIN(a.Price) as 'MinPrice'
            , CONVERT(decimal(11,0),CAST(Avg(a.Price) as decimal) ) as 'AvgPrice'
            -- Want to have Median price here

FROM
      (

      (
      select  productid, [End Price] as 'Price'
      from Table1
      where productid is not null
      )
      
      UNION ALL
      
      (
      select  productid, [Sale Amount] as 'Price'
      from Table2
      where productid is not null
      )

      ) as a
0
Comment
Question by:bobinorlando
2 Comments
 
LVL 35

Accepted Solution

by:
David Todd earned 2000 total points
ID: 39880305
Hi,

This doesn't look particularly simple or easy, but this post should help
http://www.sqlperformance.com/2012/08/t-sql-queries/median

HTH
  David
0
 
LVL 1

Author Comment

by:bobinorlando
ID: 39884000
Thanks I've seen that page and some on MSDN.
However, I now see that page links to a 2014 update that gave me a nice solution for SQL Server 2012.

http://www.sqlperformance.com/2014/02/t-sql-queries/grouped-median
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Microsoft Access has a limit of 255 columns in a single table; SQL Server allows tables with over 255 columns, but reading that data is not necessarily simple.  The final solution for this task involved creating a custom text parser and then reading…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question