SQL Join to join 2 select statments

  • Hello all,

    sorry for my query, it's a long one

    basically it consists of 2 select statements on 2 tables, each select statement gets the top 10 and self join it to the rest 90 as others.

    now I need to join the 2 statements together full join, as there's of course different top 10s in each of them.

    here's my query but it gives me weird results !! only results from the second statement and 3 NULL columns !!

    please tell me if sample data is needed.

    SELECT a.[Service Code]

    , a.[Department Total]

    , a.[Percentage]

    from

    (SELECT [Service Code]

    , [Department Total]

    , [Percentage]

    from(

    SELECT TOP 10

    [Service Code]

    ,Sum([Total Charges]) AS [Department Total]

    ,Sum([Total Charges])/(Select SUM([Total Charges]) from [ExctemedDB].[dbo].[XACTIMED-COMM] Where [Fac Name] like '%Michaels%') AS [Percentage]

    from dbo.[XACTIMED-COMM]

    Where [Fac Name] like '%Michaels%'

    GROUP BY

    [Service Code]

    ORDER BY

    [Department Total] DESC

    ) AS Q1

    UNION ALL

    SELECT

    'Other' AS [Service Code]

    ,Sum([Total Charges]) AS [Department Total]

    ,Sum([Total Charges])/(Select SUM([Total Charges]) from [ExctemedDB].[dbo].[XACTIMED-COMM]) AS [Percentage]

    from dbo.[XACTIMED-COMM]

    Where [Fac Name] like '%Michaels%'

    and

    [Service Code] NOT IN (SELECT TOP 10

    [Service Code]

    from dbo.[XACTIMED-COMM]

    Where [Fac Name] like '%Michaels%'

    GROUP BY

    [Service Code]

    ORDER BY

    Sum([Total Charges]) DESC))a

    full join

    (SELECT [Service Code]

    , [Department Total]

    , [Percentage]

    from(

    SELECT TOP 10

    [Service Code]

    ,Sum([Total Charges]) AS [Department Total]

    ,Sum([Total Charges])/(Select SUM([Total Charges]) from [ExctemedDB].[dbo].[XACTIMED-CARE] Where [Fac Name] like '%Michaels%') AS [Percentage]

    from dbo.[XACTIMED-CARE]

    Where [Fac Name] like '%Michaels%'

    GROUP BY

    [Service Code]

    ORDER BY

    [Department Total] DESC

    ) AS Q2

    UNION ALL

    SELECT

    'Other' AS [Service Code]

    ,Sum([Total Charges]) AS [Department Total]

    ,Sum([Total Charges])/(Select SUM([Total Charges]) from [ExctemedDB].[dbo].[XACTIMED-CARE]) AS [Percentage]

    from dbo.[XACTIMED-CARE]

    Where [Fac Name] like '%Michaels%'

    and

    [Service Code] NOT IN (SELECT TOP 10

    [Service Code]

    from dbo.[XACTIMED-CARE]

    Where [Fac Name] like '%Michaels%'

    GROUP BY

    [Service Code]

    ORDER BY

    Sum([Total Charges]) DESC))d

    on d.[Service Code] = a.[Service Code]

    can somebody help me please.

    Thanks

  • attaches is sample data and create table script

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply