Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Sum of Agg Function - SQL Query.

Posted on 2011-02-23
17
Medium Priority
?
351 Views
Last Modified: 2012-05-11
SQL 2008

Question Sequence : http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SQL_Server_2008/Q_26826746.html

I need to SUM of Qty Column which is Group by GenericCode Column. Value of NDC & DrugName has to pick from Default Largest Qty Column. To do this, i have attached SQL Query which thought to do this feature. But it failed.

I have attached an Excel Sheet - SampleDate.xls
In which Tab : CurrentDatabase - which is directly extracted from database by the query
select * from vw_Test3

From the Tab : DerivedFromQuery - is the output which i got from the attached Query.

Tab - SampleExpectedData :- Explains what we expect from the Query.



with p as (
select    
   TR.[Generic Code],  
   TR.NDC,     
   TR.[Drug Name],
   Sum(cast(TR.[Qty] as int)) as Qty  
from  vw_Test3 TR      
Group By TR.[Generic Code], TR.NDC,TR.[Drug Name] 
)
select x.[Generic Code], x.NDC, x.[Drug Name], y.Qty from 
(
select p.*, row_number() over (partition by [Generic Code] order by Qty desc) rn from p
) x 
left join 
(
select [Generic Code], sum(cast(Qty as int)) Qty from p group by [Generic Code]
) y 
on x.[Generic Code]=y.[Generic Code]
where rn=1;

Open in new window

SampleData.xls
0
Comment
Question by:chokka
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 8
17 Comments
 
LVL 41

Expert Comment

by:Sharath
ID: 34964310
I think this is sufficient. Check this.
SELECT * 
FROM   (SELECT *, 
               SUM(Qty) 
                 OVER(PARTITION BY [Generic Code] )   sum_Qty, 
               ROW_NUMBER() 
                 OVER(PARTITION BY [Generic Code] ORDER BY Qty) rn 
        FROM   vw_Test3) t1 
WHERE  rn = 1

Open in new window

0
 

Author Comment

by:chokka
ID: 34964401
Thanks

If you seen the Excel Sheet Tab : Derived from Query - I have 251 rows affected.

Your Query, and the Query which i attached results the same number of rows.

Query doesn't give exact results. It is ignoring .. NULL Values in the
GenericCode,DrugName Columns
0
 

Author Comment

by:chokka
ID: 34964856
Sharath123 :- I am able  to find the issue.

In my Query, is there anyway to add a Condition by mentioning

IF GenericCode Column is NULL , Ignore these Steps.

0
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

 
LVL 41

Expert Comment

by:Sharath
ID: 34964928
Add a filter on Generic Code is NOT NULL.
SELECT * 
  FROM (SELECT *, 
               SUM(Qty) 
                 OVER(PARTITION BY [Generic Code] )   sum_Qty, 
               ROW_NUMBER() 
                 OVER(PARTITION BY [Generic Code] ORDER BY Qty) rn 
          FROM vw_Test3 
         WHERE [Generic Code] IS NOT NULL) t1 
 WHERE rn = 1

Open in new window

0
 

Author Comment

by:chokka
ID: 34965579
Is there anyway for me to merge these two SQL Query - by using UNION ALL Keyword.

I am aware by keeping the first set of SQL QUery into another View and then go for Union All .

Too many views affects the performance of SQL ..!
with p as (
select    
   TR.[Generic Code],  
   TR.NDC,     
   TR.[Drug Name],
   Sum(cast(TR.[Qty] as int)) as Qty  
from  vw_Test3 TR
where TR.[Generic Code] is not null      
Group By TR.[Generic Code], TR.NDC,TR.[Drug Name] 
)
select x.[Generic Code], x.NDC, x.[Drug Name], y.Qty from 
(
select p.*, row_number() over (partition by [Generic Code] order by Qty desc) rn from p
) x 
left join 
(
select [Generic Code], sum(cast(Qty as int)) Qty from p
where [Generic Code] is not null
 group by [Generic Code]
) y 
on x.[Generic Code]=y.[Generic Code]
where rn=1;
--UNION ALL
select * from vw_Test3 where [Generic Code] IS NULL

Open in new window

0
 
LVL 41

Expert Comment

by:Sharath
ID: 34966456
Did you see any issue with my suggested query? I don't understand why you want to query the table multiple times when you can get the result in a straight way.
0
 

Author Comment

by:chokka
ID: 34971353
In your suggested query,

Number of rows affected are correct. But Values which summed in Qty is not perfect.

I feel hard to check row by row to find the issues .. but there is mismatch on the records what we expect and what it generated.

0
 
LVL 41

Expert Comment

by:Sharath
ID: 34971963
You want the sum of Qty for every Generic Code.
You want to display the record with max Qty for every Generic Code.
You don't want NULL Generic Code records.

Is my understanding correct?
0
 

Author Comment

by:chokka
ID: 34972005
Yes sir...

For Example :-

Generic Code      NDC      Drug Name                                               Qty
392                    68180051703          LISINOPRIL 40 MG TABLET          60
392                    64679094201      LISINOPRIL 40 MG TABLET          30
392                    64679094201      LISINOPRIL 40 MG TABLET          30
            

Expected output :-
      
392                  68180051703          LISINOPRIL 40 MG TABLET          120

In the Expected Output, You can see , we cumulated with Maximum Qty listed GenericCode / DrugName.
0
 
LVL 41

Expert Comment

by:Sharath
ID: 34972025
Can you post at least one such mismatched Qty record with my query?
0
 

Author Comment

by:chokka
ID: 34972367
I am checking row by row .. few issues are mismatching with NDC


Generic Code      NDC      Drug Name      Qty      sum_Qty      rn
393      64679092801      LISINOPRIL 5 MG TABLET           30      120      1

Generic Code      NDC      Drug Name      Qty      sum_Qty      rn
1775      65862003001          GLYBURIDE 5 MG TABLET            30      30      1
0
 
LVL 41

Expert Comment

by:Sharath
ID: 34972399
Can you post the records from your view vw_Test3 for Generic Code 393?
0
 

Author Comment

by:chokka
ID: 34972500
Actually both query output has issues ..! I  have taken the output in an excel sheet and trying to find out duplicate records.
0
 
LVL 41

Expert Comment

by:Sharath
ID: 34972523
My bad. I missed the DESC keyword. try this.
SELECT * 
  FROM (SELECT *, 
               SUM(Qty) 
                 OVER(PARTITION BY [Generic Code] )   sum_Qty, 
               ROW_NUMBER() 
                 OVER(PARTITION BY [Generic Code] ORDER BY Qty desc) rn 
          FROM CurrentDatabase 
         WHERE [Generic Code] IS NOT NULL) t1

Open in new window

0
 

Author Comment

by:chokka
ID: 34973393
Sharath

SELECT *
  FROM (SELECT *,
               SUM(Qty)
                 OVER(PARTITION BY [Generic Code] )   sum_Qty,
               ROW_NUMBER()
                 OVER(PARTITION BY [Generic Code] ORDER BY Qty desc) rn
          FROM vw_Test3  
         WHERE [Generic Code] IS NOT NULL) t1



This query returns 344 Rows. Which is completely wrong.
0
 
LVL 41

Accepted Solution

by:
Sharath earned 2000 total points
ID: 34973440
missed the rn = 1 filter.
SELECT * 
  FROM (SELECT *, 
               SUM(Qty) 
                 OVER(PARTITION BY [Generic Code] )   sum_Qty, 
               ROW_NUMBER() 
                 OVER(PARTITION BY [Generic Code] ORDER BY Qty) rn 
          FROM CurrentDatabase 
         WHERE [Generic Code] IS NOT NULL) t1 
 WHERE rn = 1

Open in new window

0
 

Author Comment

by:chokka
ID: 35181883
i just missed it, will check it and close this question.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

715 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