Use of SUM and COUNT with GROUP BY

All,
I have a set like below:
State DOB StartDt EndDt Desc Category MemberID SubID Code
NC 2003-01-30 2014-01-01 2014-01-31 Child B 123456 2 38
NC 2003-01-30 2014-01-01 2014-01-31 Child B 123456 2 39
NC 2003-01-30 2014-02-01 2014-05-31 Child B 123456 2 38
NC 2003-01-30 2014-02-01 2014-05-31 Child B 123456 2 39
NC 2003-01-30 2014-06-01 2014-07-31 Child B 123456 2 38
NC 2003-01-30 2014-06-01 2014-07-31 Child B 123456 2 39
NC 2014-01-17 2014-01-01 2014-07-31 Infant S 456789 1 49
NC 2014-02-04 2014-02-01 2014-07-31 Infant S 246376 3 49
-- MemberID and SubID identify 1 member
-- Member 123456 has 2 distinct "Code" i.e. 38,39 but each code has different "StartDt" and "EndDt"
-- Expected Result
State Desc Category CountOfDistinctCode TotalMonthsEnrolled
NC Child B 2 (38 and 39 for same member) 7 months (1 + 4 + 2) (Difference between StartDt and EndDt:1 (1/31/2014 - 1/1/2014) + 4 (5/31/2014 - 2/1/2014).. )
NC Infant S 2 (Same code 49 but different member) 13 months (7+6) (7/31/2014 - 1/1/2014 = 7 months + 7/31/2014 - 2/1/2014 = 6 months)
I tried doing a count of distinct Code and the summing up the member months, grouped by State, Desc, Category, but I am not able to get 2 and 7 for child, it somehow calculates Months as 14 (7+7). Please let me know what you guys suggest.

OK, so we need a different approach. We need a table of numbers, a concept that I discuss here:
http://www.sommarskog.se/arrays-in-sql-2005.html#numbersasconcept
(Only read down to the next header.)
We join the numbers to temp table with BETWEEN over the numbers. Then we count the distinct combination of member ID and number.
We also need to make an adjustment how to build the string for the DISTINCT. I initially assumed that your columns were integer, why I used str() which produces a right-adjusted fixed-length string of 10 characters. (The default, you can specify a different
width as the second parameter.) But str() expects a float value as input, and will fail if for instance member id would be non-numeric. We cannot just concatenate the strings, since in that case (MemberID, SubID) = ('12345', '61') would be
the same as ('123456', '1'). So we must convert to char to get fixed length. All that said, and some more test data added, here is a solution:
CREATE TABLE #Test
[State] CHAR(2),
DOB DATE,
StartDt DATE,
EndDt DATE,
[Desc] VARCHAR(8),
Category CHAR(1),
MemberID VARCHAR(10),
SubID VARCHAR(2),
Code VARCHAR(5)
INSERT INTO #Test
VALUES
('NC', '20130130', '20140101', '20140120', 'Child', 'B', '123456', '2', '38'),
('NC', '20130130', '20140121', '20140131', 'Child', 'B', '123456', '2', '39'),
('NC', '20130130', '20140201', '20140531', 'Child', 'B', '123456', '2', '38'),
('NC', '20130130', '20140401', '20140613', 'Child', 'B', '123456', '2', '39'),
('NC', '20130130', '20140601', '20140731', 'Child', 'B', '123456', '2', '38'),
('NC', '20130130', '20140614', '20140731', 'Child', 'B', '123456', '2', '39'),
('NC', '20130129', '20140601', '20140731', 'Child', 'B', '9123456', '1', '38'),
('NC', '20130129', '20140614', '20140831', 'Child', 'B', '9123456', '1', '39'),
('NC', '20140117', '20140101', '20140731', 'Infant', 'S', '456789', '1', '49'),
('NC', '20140204', '20140201', '20140731', 'Infant', 'S', '246376', '3', '49')
SELECT * FROM #Test ORDER BY MemberID, StartDt, EndDt
SELECT
[State]
, [Desc]
, Category
, COUNT(DISTINCT convert(char(10), MemberID) +
convert(char(2), SubID) +
convert(char(5), Code)) AS TotalCnt
, COUNT(DISTINCT convert(char(10), MemberID) +
convert(char(2), SubID) +
str(N.Number)) AS CalMonths
FROM #Test t
JOIN Numbers N ON N.Number BETWEEN
datediff(MONTH, '19000101', t.StartDt) AND
datediff(MONTH, '19000101', t.EndDt)
GROUP BY [State], [Desc], Category
go
DROP TABLE #Test
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • Max, Min and Count with Group By

    Hello,
    i want the max, min and count of a table, which is grouped by a column
    I need a combination of these two selects:
    select
         max(COUNTRY_S) MAXVALUE,
         min(COUNTRY_S) MINVALUE
    from
         tab_Country
    select
         count(*)
    from
         (select COUNTRY_TXT from tab_Country group by COUNTRY_TXT) ;
    The result should be one row with the max and min value of the table and with the count of the grouped by table, not the max and min of each group! - i hope you understand my question?
    Is this possible in one SQL-select?
    Thank you very much
    Best regards
    Heidi

    Hi, Heidi,
    HeidiWeber wrote:
    Hello,
    i want the max, min and count of a table, which is grouped by a column
    I need a combination of these two selects:
    select 
         max(COUNTRY_S) MAXVALUE, 
         min(COUNTRY_S) MINVALUE 
    from 
         tab_Country 
    select 
         count(*) 
    from 
         (select COUNTRY_TXT from tab_Country group by COUNTRY_TXT) ; 
    The result should be one row with the max and min value of the table and with the count of the grouped by table, not the max and min of each group! - i hope you understand my question?
    Is this possible in one SQL-select?
    Thank you very much
    Best regards
    Heidi
    It's not clear what you want.  Perhaps
    SELECT  MAX (country_s)               AS max_country_s
    ,       MIN (country_s)               AS min_country_s
    ,       COUNT (DISTINCT country_txt)  AS count_country_txt
    FROM    tab_country
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Count(*) with group by max(date)

    SQL> select xdesc,xcust,xdate from coba1 order by xdesc,xcust,xdate;
    XDESC XCUST XDATE
    RUB-A 11026 01-JAN-06
    RUB-A 11026 05-JAN-06
    RUB-A 11026 08-JAN-06
    RUB-A 11027 10-JAN-06
    RUB-B 11026 02-JAN-06
    RUB-B 11026 08-JAN-06
    RUB-B 11026 09-JAN-06
    RUB-C 11027 08-JAN-06
    I want to make sql that result :
    XDESC     COUNT(*)
    RUB-A     2
    RUB-B 1
    RUB-C 1
    Criteria : GROUPING: XDESC XCUST AND MAX(DATE)
    bellow mark *** that was selected in count.
    XDESC XCUST XDATE
    RUB-A 11026 01-JAN-06
    RUB-A 11026 05-JAN-06
    RUB-A 11026 08-JAN-06 ***
    RUB-A 11027 10-JAN-06 ***
    ---------------------------------------------------------COUNT RUB-A = 2
    RUB-B 11026 02-JAN-06
    RUB-B 11026 08-JAN-06
    RUB-B 11026 09-JAN-06 ***
    ---------------------------------------------------------COUNT RUB-B = 1
    RUB-C 11027 08-JAN-06 ***
    --------------------------------------------------------COUNT RUB-C = 1
    Can Anybody help ?
    I tried :
    select xdesc,max(xdate),count(max(xdate)) from coba1 group by xdesc
    ERROR at line 1:
    ORA-00937: not a single-group group function
    Thank

    This one is duplicate. see the following link
    Count(*) with group by max(date)
    Thanks

  • DIFFERENCE BETWEEN SUM AND COUNT IN SQL

    DIFFERENCE BETWEEN SUM AND COUNT IN SQL
    WHAT IS THE DIFFERENCE VERIFY IN DETAIL/

    21031980, I suggest you upgrade your computer sothat you can access google.
    lol.
    wtfpwnd.Google is also helpful for understanding the strange
    acronyms that show up around here lately (yes, I did
    find and understand this one). :-)Haha, sorry!
    It's the inner-gamer in me rearing its ugly head...
    :-)

  • Can I use Adobe Premiere and Photoshop (with cloud license) on more thn one computer.

    Can I use Adobe Premiere and Photoshop (with cloud license) on more than one computer? WHen on the oroad I would like to use it n my laptop, while I installed on the desktop.

    Hi Kasiah,
    As per the EULA accepted while you launch Adobe applications you can download & install on 2 systems but can use on one at the same time.
    Source:http://www.adobe.com/in/products/creativecloud/faq.html
    Let me know if you have any questions on this.
    Cheers~!
    -Mandhir

  • TS1347 Have been using an iPhone and syncing with Outlook for several years.  Since downloading latest version of iTunes, contacts and calendars are not syncing.  Both items show to be checked for syncing.  Any suggestions?

    Have been using an iPhone and sysncing with Outlook through iTunes for several years.  Downloaded the recent update to iTunes and now sycing of contacts & calendars is not occuring.  I did see that i had to recheck to sync contacts and calendars again and have done this, but still no syncing is occuring.  Any suggestions?

    Hi Brian!
    I have an article here for you that addresses your issue and can help you troubleshoot this further:
    iPhone, iPad, iPod touch: Troubleshooting contact and calendar syncing via USB on Windows
    http://support.apple.com/kb/HT1692
    Thanks for coming to the Apple Support Communities!
    Regards,
    Braden

  • How to upload a file into server using j2ee jsp and servlet with bean?

    How to upload a file into server using j2ee jsp and servlet with bean? Please give me the reference or url about how to do that. If related to struts is more suitable.
    Anyone help me please!

    u don't need j2ee and struts to do file uploading. An example is as such
    in JSP. u use the <input> file tag like
    <input type="file"....>You need a bean to capture the file contents like
    class FileUploadObj {
        private FormFile srcFile;
        private byte[] fileContent;
        // all the getter and setter methods
    }Then in the servlet, you process the file for uploading
        * The following loads the uploaded binary data into a byte Array.
        FileUploadObj form = new FileUploadObj();
        byte[] byteArr = null;
        if (form.signFile != null) {
            int filesize = form.srcFile.getFileSize();
            byteArr = new byte[filesize];
            ByteArrayInputStream bytein = new ByteArrayInputStream (form.srcFile.getFileData());
            bytein.read(byteArr);
            bytein.close();
            form.setFileContent(byteArr);
        // Write file content using Writer class into the destination file in the server.
        ...

  • How to use the eventing and databag with a WAS 6.20 ?

    How to use the eventing and databag with a WAS 6.20 ?
    Is what there is a good guide for these services?
    Thank's

    In the raise event you can pass the value
    like below.
    <SCRIPT>
    function raiseEvt(value1){
    if(window.document.domain == window.location.hostname){
    if ( document.domain.indexOf(".") > 0 ) document.domain = document.domain.substr(document.domain.indexOf(".")+1);
       EPCMPROXY.raiseEvent( "urn:com.sap:BWEvents","BWiViewevent", value1, null );
      // alert('tree domain'+document.domain);
    </SCRIPT>
    and in the
    subscribe event you can get the values like below.
    <script language="javascript">
    if(window.document.domain == window.location.hostname){
    document.domain = document.domain.substring(document.domain.indexOf('.')+1);
        EPCMPROXY.subscribeEvent("urn:com.sap:BWEvents","BWiViewevent", window, "myreceiveEvent");
    function myreceiveEvent( eventObj ) {
          document.forms[0].gp_hidden.value = eventObj.dataObject;
    </script>
    Also look at the following link for a complete documentation.
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/documents/a1-8-4/Enterprise%20Portal%20Client.pdf
    Regards
    Raja

  • HT5361 Been using mail forever and only with my gmail account. All of a sudden, all my inbox mails are missing except for anything after yest night. I log into gmail on safari and everything is there but not on my mac or iphone in mail

    Been using mail forever and only with my gmail account. All of a sudden, all my inbox mails are missing except for anything after yest night. I log into gmail on safari and everything is there but not on my mac or iphone in mail

    Same problem in 8.1.3
    Apple help!

  • How shall I use my IMac and MacBookPro, with synchronized files

    Hi, how shall I use my IMac and MacBookPro, with synchronized files? I used to work at home and office with those to machines and finally always have different version of my documents. Is there any dispositive that I should use, where all my files are moving with me? os there is something to synchronized the computers using WiFi or bluetooth?

    The following has instructions: OS X Mavericks: Share your Internet connection

  • Why it is keep asking for Username and Password but i didn't use any username and password with my database.

    Why it is keep asking for Username and Password but i didn't use any username and password with my database. Please help me i m very frustrated right now please help anybody. I m new in this.,

    Hi,
    Please check below threads:
    Crystal Report Layout asking for Login Info
    SAP B1 ask for credentials to print or to preview Crystal Reports report

  • Cannot use double tap and move with one finger to select text in Mountain Lion

    I've been using OS X in my Macbook Pro since Snow Leopard, and if I choose "tap with one finger to click", I can use double tap and move with one finger to select text if the cursor is between text.
    It works in Snow Leopard,and Lion However, in Mountain Lion, this doesn't work!! I have to click in the bottom right corner of my trackpad  in order to select the text.
    Can anyone get this fixed ?
    Thanks.

    Caolei,
    I don't know if you'll ever see this, but thank you! I hope this helps somebody else down the line, too.
    re. "I can use double tap and move with one finger to select text if the cursor is between text."
    I've been trying to figure out how to select text with tapping and without clicking.
    This did the trick.
    It's quite finicky to not select a space in between words.
    Zooming in does seem to help (two finger double tapping in a body of text may trigger a SmartZoom and zoom the current frame of text to fill the screen, if anybody doesn't know this.)
    ((There's a smartMagnifyWithEvent Cocoa NSEvent that's not universally supported across all applications for noob OS X developers like me.))
    I haven't been able to find the part about double tapping between text to begin a selection (which seems to work best when double tapping directly next to a letter) anywhere in the help system on or online. I probably just missed it, though.
    Clicking with the built-in trackpad on my MacBook Pro w/ Retina or Magic Mouse just takes too much pressure for an old-time touch typist like me.
    As an aside, I've been trying BetterTouchTool and MagicPrefs to enable one finger tap on the Magic Mouse. BetterTouchTool seems to trigger text selection unwantedly and randomly, though.
    The whole mystique of Mac / Apple being intuitive and user-friendly seems to be one of the greatest marketing coups / unbelievable con jobs of the last century.
    I'm actually somewhat qualified to express an opinion as a software engineer with a degree in Computer Science and programming and user interface design experience in Windows, UNIX, web, Android and other systems, and now OS X and iOS. I could go on and on and on but I won't other to say that I still find Macs buggy and hard to use. I'm now finding that my new iPhone 5 is just as big of a pain (i.e. big thumbs missing landscape keyboard in Contacts.) Of course, I like flexibility and options and custom workflows and more than one way to do things and simply being able to do things at all, so I'm also actually somewhat biased. Sorry for the rant...
    Cheers,
    Hal

  • SUM and count next to each other

    SUM and count next to each other
    I would like to have the measurements SUM and COUNT cells being next to each other.
    As a default it shows up like this:
    .......SUM............. COUNT
    ......RegionA RegionB RegionA RegionB
    2000..... $..... $..... nn..... nn
    2001..... $..... $..... nn..... nn
    2002..... $..... $..... nn..... nn
    Can I change this somehow to:
    ......RegionA.....RegionB
    ......SUM COUNT ...SUM COUNT
    2000...$....nn......$... nn
    2001...$....nn......$... nn
    2002...$....nn......$... nn
    thnx
    Endre

    Select your axis "Region" and move it over (i.e. on top of) your data points (SUM, COUNT, etc.).

  • Can i use my mac and pc with a cloud app?

    can i use my mac and pc with a cloud app

    Yes.
    http://www.adobe.com/products/creativecloud/faq.html
    Yes, as a member of Creative Cloud, you get many benefits that you do not get when you purchase a traditional shrinkwrapped product:
    An ever-expanding membership that provides access to Adobe's latest products, services, features, and workflows as soon as they are available. You no longer have to wait 12, 18, or 24 months for the latest innovations.
    Access to both the Mac OS and Windows® versions of the desktop applications and the ability to install them on your primary computer and one backup computer. So, if you have a Mac at home and a PC at work, you can install your applications on both as long as they are not running at the same time. See the product license agreements page for more information.

  • Using JCheckBox, JButton and JTextArea with JDBC

    Hello shlumph and SoulTech2012.
    thanks for the reply. I�m wondering do any of you have links to web pages that include tutorials and source code on using JCheckBox, JButton and JTextArea with JDBC. would any of you who have experience with using JCheckBox, JButton, JTextArea and JDBC together be able to give me a few tips on how to select certain data from a table using JCheckBox, JButton and display the data in a JTextArea? examples of such data could be CD/DVD/Game data - i want users of my video library system to be able to view CD/DVD/Game information by name, age category, type and year. Users should be able to click on a check box (e.g. view by name, age category, type or year) and press a button. What would happen then is that data from the Product table would appear in the text area (which could be placed beneath the check box + button inside a frame and/or panel).
    Thank you very much for your help.

    Quit triple posting and cross posting your questions all over the forum. You already have a posting in this forum on this topic and another posting in the Swing forum and another posting in the Programming forum.

Maybe you are looking for

  • Why will airplay not work from my desktop to apple tv after I installed the new update?

    After I installed the new Updates to Itunes, I can no longer use airplay from my desktop to my Apple TV, it goes orange and says it does not work. Please help! They are both on the same network and Apple TV has been updated.

  • Selection Screen for Infopackage schedule

    Hi Guys, I want to create a selection screen which appears when a user schedules an infopackage so that the user can enter the posting period, year from and to values and the load takes place for those values. I want to do this so that the infopackag

  • VFRB / Billing output issues

    When running retro billing VFRB, entries in NAST (Output) table  has been updated with entries even before the debit or credit documents have been created. So we have entries in NAST with object id  $000000001 and so on instead of the correct billing

  • Detect the end of flvplayback

    i have an flvplayback component on stage, named the instance flvPlayer and added this code to frame 1, so a video loads in it. flvPlayer.source = "clip1.flv"; the videos plays from the local folder perfectly. I need a code that when the video ends, i

  • Plz! Icloud has ruined my life:((

    I need to separate myself from an old apple Id but I want to preserve my contacts, messages and calendars... I have started a new account but I can't separate them??? Plz help me! I'm so frustrated with the Cloud: