0

I want to show all the values from both tables([JC_ItemDSP10days],[JC_ItemDSP30Days])

when I run this below query, it returns 14210 Rows

select 
    itemid,sum(qtysold) [NineDaysSold]
from 
    [HQMatajer].[dbo].[JC_ItemDSP10days]
group by ItemID

when I run this query, it returns 16455 Rows

select 
    itemid,sum(qtysold) [ThirtyDaysSold]
from 
    [HQMatajer].[dbo].[JC_ItemDSP30Days]
group by ItemID

Now i want to show all the records from both table, when JC_ItemDSP10days.ItemID=JC_ItemDSP30Days.ItemID,as well as if the records are not in either one of the table also it has to show the result

This is what i tried

select 
    ItemID =isnull(nineDays.itemid,thirtyDays.ItemID),
    CONVERT(DECIMAL(10,2),sum(nineDays.qtysold))  [NineDaysSold],
    CONVERT(DECIMAL(10,2),sum(thirtyDays.qtysold)) [ThirtyDaysSold]
from 
    [JC_ItemDSP10days] nineDays
FULL outer JOIN [HQMatajer].[dbo].[JC_ItemDSP30Days] thirtyDays on nineDays.ItemID=thirtyDays.ItemID
group by nineDays.ItemID,thirtyDays.ItemID
order by ItemID

But the result is wrong

Result

This is the actual value of ItemID=9 From the first two query result

Result2

1 Answer 1

2

Because you will have multiple rows for the same itemid in each table, using the full join you will get duplicates as matches overlap which will inflate your aggregates.

Consequently, you need to do your aggregation on each dataset before joining the results together. In the simplest form (In terms of seeing what is being done) what you need to do logically is the following:

select itemid = isnull(nineDays.itemid,thirtyDays.ItemID)
        ,nineDays.NineDaysSold
        ,thirtyDays.ThirtyDaysSold
from (select itemid
                ,sum(qtysold) as NineDaysSold
        from [HQMatajer].[dbo].[JC_ItemDSP10days]
        group by ItemID
        ) as nineDays
    full outer join (select itemid
                            ,sum(qtysold) as ThirtyDaysSold
                    from [HQMatajer].[dbo].[JC_ItemDSP30Days]
                    group by ItemID
                    ) as thirtyDays
        on(nineDays.itemid = thirtyDays.itemid);

Which is more traditionally done with the use of Common Table Expressions:

with nineDays as
(
    select itemid
            ,sum(qtysold) as NineDaysSold
    from [HQMatajer].[dbo].[JC_ItemDSP10days]
    group by ItemID
), thirtyDays as
(
    select itemid
            ,sum(qtysold) as ThirtyDaysSold
    from [HQMatajer].[dbo].[JC_ItemDSP30Days]
    group by ItemID
)
select itemid = isnull(nineDays.itemid,thirtyDays.ItemID)
        ,nineDays.NineDaysSold
        ,thirtyDays.ThirtyDaysSold
from nineDays
    full outer join thirtyDays
        on(nineDays.itemid = thirtyDays.itemid);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.