Solved

Median with Union

Posted on 2014-02-22
2
194 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 500 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

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…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

803 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