Sql Query : Sum , all the possible combination of rows in a table

SQL Server 2008 R2
Sample Table structure
create table TempTable
ID int identity,
value int
insert into TempTable values(6)
insert into TempTable values(7)
insert into TempTable values(8)
insert into TempTable values(9)
insert into TempTable values(10)
I actually want something like below,
that It returns rows such that, it has the sum of all the remaining rows , as shown below.
I will ignore the repeated rows.
6+7
6+8
6+9
6+10
6+7+8
6+7+9
6+7+10
6+8+9
6+8+10
6+9+10 
6+7+8+9
6+7+8+9+10

This makes no sense. What about NULLs? What about duplicate values? You have rows, so you have many combinations. We know that this set totals to 39, so there is no subset totals to half of any odd number.  19.5
in this case. 
None of your examples are
even close! 
 6+7 = 13
the remaining rows 8+9+10 = 27, so you failed! 
Want to try again?
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Show all the possible combinations of n elements in an array???

    If I have an array of n elements, how to show all the possible combinations of n elements.
    What is the java library for doing the combinations??
    For example,
    public class CombinationTest
    {     public static void main(String[] args)     
         {     ArrayList letters = new ArrayList();
              leters.add("s1");
              leters.add("s2");
              leters.add("s3");
    Find all the combinations of 3 elements: C(3,2). Here's the result:
    1) s1, s2
    2) s1, s3
    3) s2, s3
    }

    There isn't a built-in API method for this. Still, combinations are pretty easy. Pseudocode (borrowing notation from ML and GJ, and assuming immutable sets): Set<Set<Object>> getCombinations(int itemsInCombo, Set<Object> itemsToCombine)
        // Handle base case and exceptional cases
        if (itemsInCombo = 0) return Set.emptySet();
        if (itemsInCombo < 0) throw new Exception("?!");
        // Recursive case
        Object o = itemsToCombine.first(); // use iterator - may throw exception
        // Get combos with first element
        Set<Set<Object>> rv = map (x => x.add(o)) getCombinations(itemsInCombo - 1, itemsToCombine.remove(o));
        // Add combos without first element
        rv.add(getCombinations(itemsInCombo, itemsToCombine.remove(o)));
        return rv;
    }

  • SQL Query to find the Delta between 2 rows

    Can the below be possible? If so can you help me writing aSQL Query to do so…
    I have data in spreadsheet which is pulled off from the database (data from more than one table with joins); send it to the different teams. They will check the data n update the spreadsheet if necessary and send it back to me.
    I have to find the changes and update the database from the provided spreadsheet accordingly. Changes can be on different columns on each set of row.
    Example:
    DataFrom
    ServerName
    Branch_Name
    Application_Name
    Server Status
    Application_Status
    App_Environment
    Tier
    SQL Query
    abcdef
    app
    adp
    Deployed
    Deployed
    Production
    silver
    Excel
    abcdef
    app
    adp
    Deployed
    Deployed
    Development
    Bronze
    DataFrom
    ServerName
    Branch_Name
    Application_Name
    Server Status
    Application_Status
    App_Environment
    Tier
    SQL Query
    Hijkl
    app
    adp
    Deployed
    Deployed
    Production
    Gold
    Excel
    Hijkl
    app
    Dep
    Deployed
    Deployed
    Production
    Gold
    DataFrom
    ServerName
    Branch_Name
    Application_Name
    Server Status
    Application_Status
    App_Environment
    Tier
    SQL Query
    Xzy
    app
    Dep
    Deployed
    Deployed
    Production
    Silver
    Excel
    Xzy
    App
    Dep
    Deployed
    Deployed
    Development
    Silver
    Above scenario is an example what I am look to do with sql script? Opinions/queries accepted…
    There are 1200+ rows to compare it manually which is a pain.
    Thanks.

    Columns are different, when the contain multiple distinct values.
    SELECT COUNT(DISTINCT Name) ,
    COUNT(DISTINCT GroupName) ,
    COUNT(*)
    FROM HumanResources.Department;
    Without a concise and complete example (table DDL and sample data insert statements), it's hard to tell what the correct solution could be..
    DECLARE @Sample TABLE ( SetID INT, ServerID INT, ApplicationID INT );
    INSERT INTO @Sample
    VALUES ( 1, 1, 1 ),
    ( 1, 1, 1 ),
    ( 2, 1, 1 ),
    ( 2, 1, 2 ),
    ( 3, 1, 1 ),
    ( 3, 2, 1 );
    WITH Evaluate AS
    SELECT SetID,
    COUNT(DISTINCT ServerID) AS Servers,
    COUNT(DISTINCT ApplicationID) AS Applications
    FROM @Sample
    GROUP BY SetID
    SELECT S.*,
    CASE WHEN E.Servers != 1 THEN 1 ELSE 0 END AS ServersDifferent,
    CASE WHEN E.Applications != 1 THEN 1 ELSE 0 END AS ApplicationsDifferent
    FROM @Sample S
    INNER JOIN Evaluate E ON S.SetID = E.SetID
    ORDER BY S.SetID;

  • Looking for a SQL query to get all the possible Alert Messages from the Rules in a Management Pack

    For reporting, I'm looking to get a SQL query of all the possible Alert Messages for Rules configured in a Management Pack (not necessarily the ones that have thrown alerts).  I can do this for Monitors, but not for Rules. 
    The configured alert messages for the Management Pack Monitors
    go like this:  ManagementPack > MonitorView> RuleModule > RuleModule.Alert Message > Localized Text
    The configured alert messages for the Management Pack Rules
    should go something like this, but there is a missing link:  ManagementPack > RuleView > RuleModule > ? Missing Link ? > Localized Text
    The Rules are tied to the Module, but I don't see a connection from the RulesModule to the Alert Message that I see in the LocalizedText. The Rule names do not always equal the Alert name. 
    Can someone provide the missing link?

    Hi,
    please try below powershell code to find the corresponding management pack for specific alert:
    $Alert = get-scomalert | where {$_.Name -like 'Agent Proxy Not Enabled*'} | select -first 1
    If ($alert.IsMonitorAlert -eq "True") {
    write-host "Ths is a monitor-generated alert"
    get-scommonitor -ID $Alert.MonitoringRuleID | select Enabled, DisplayName, ManagementPack
    else
    write-host "This is a rule-generated alert"
    get-scomrule -ID $Alert.MonitoringRuleID | select Enabled, DisplayName, ManagementPack
    In addition, please also refer to the below link:
    http://blogs.technet.com/b/mazenahmed/archive/2011/12/02/using-powershell-to-map-opsmgr-active-alert-to-its-corresponding-rule-monitor-and-management-pack-name.aspx
    Regards,
    Yan Li
    Regards, Yan Li

  • SQL query to list the "Administrative category" field for all applications

    yesterday i started a thread to list the "Optional reference" field for all cm applications in a SSRS report. I've got the query with the help of Torsten.
    https://social.technet.microsoft.com/Forums/en-US/00419e6e-e3c2-4b80-b6af-2a24ced1032d/sql-query-to-list-the-optional-reference-field-of-all-packages-in-cm-2012?forum=configmanagersdk
    But again today, i'm looking for a way to get "Administrative category" field in a SSRS report. Could someone point me to the right direction ?
    Kindly mark as answer/Vote as helpful if a reply from anybody helped you in this forum. Delphin

    Hi,
    You could monitor the SMSProv.log when you check the category of an application. It shows that SQL query the SCCM provider used is related to function fn_ListCategoryInstances.
    Best Regards,
    Joyce

  • Give me the sql query which calculte the table size in oracle 10g ecc 6.0

    Hi expert,
    Please  give me the sql query which calculte the table size in oracle 10g ecc 6.0.
    Regards

    Orkun Gedik wrote:
    select segment_name, sum(bytes)/(1024*1024) from dba_segments where segment_name = '<TABLE_NAME>' group by segment_name;
    Hi,
    This delivers possibly wrong data in MCOD installations.
    Depending on Oracle Version and Patchlevel dba_segments does not always have the correct data,
    at any time esp. for indexes right after being rebuild parallel (Even in DB02 because it is using USER_SEGMENTS).
    Takes a day to get the data back in line (never found out, who did the correction at night, could be RSCOLL00 ?).
    Use above statement with "OWNER = " in WHERE for MCOD or connect as schema owner and use USER_SEGMENTS.
    Use with
    segment_name LIKE '<TABLE_NAME>%'
    if you like to see the related indexes as well.
    For partitioned objects, a join from dba_tables / dba_indexes to dba_tab_partitions/dba_ind_partitions to dba_segments
    might be needed, esp. for hash partitioned tables, depending on how they have been created ( partition names SYS_xxxx).
    Volker

  • SQL Query to get the # of files in folders in a library

    Anyone has the SQL query to list the number of files in each folders in a SharePoint library?

    Technically it's a grey area of support as MS don't mind you doing it but won't help you if you encounter problems, the script is much better though.
    Scratch that, the script isn't that good. It's using .items which won't work on large lists and is slow. The version below is untested but should be significantly faster and work on large lists.
    $starttime = Get-Date
    #Creating new site object
    $siteurl = Read-Host "Enter the name of your site and press enter"
    $site = New-Object Microsoft.SharePoint.SPSite($siteurl)
    #Assigning all webs (sites) to $webs
    $webs = $site.Allwebs
    #System Libraries defined so they won't be touched##
    $systemlibs =@("Converted Forms", "Customized Reports", "Documents", "Form Templates",
    "Images", "List Template Gallery", "Master Page Gallery", "Pages",
    "Reporting Templates", "Site Assets", "Site Collection Documents",
    "Site Collection Images", "Site Pages", "Solution Gallery",
    "Style Library", "Theme Gallery", "Web Part Gallery", "wfpub")
    Write-Host "Total number of webs that will be traversed: " $webs.count
    $DocLibsCount = 0
    $DocLibwItems = 0
    $totalitems = 0
    $subfolderitems = 0
    foreach($web in $webs)
    $listcoll = $web.lists
    foreach($list in $listcoll)
    if($list -eq $null)
    Write-Host
    else
    $base = $list.GetType()
    if($base.name -eq "SPDocumentLibrary")
    if ($systemlibs -contains $list)
    { continue}
    else
    $DocLibsCount += 1
    $totalitems += $List.itemcount
    $name = $list.Title
    $folders = $web.GetFolder($name).SubFolders
    for($etr = 0;$etr -lt $folders.count; $etr++)
    if($folders[$etr].Name -ne "Forms")
    Write-Host "Processing SubFolder ItemCount" -ForegroundColor Red
    $tempcount = $folders[$etr].ItemCount
    $subfolderitems += $tempcount
    Write-Host
    Write-Host
    Write-Host "Total # of Document Libraries: " $DocLibsCount -ForegroundColor Green
    Write-Host "Total # of Document Libraries that contain items: " $DocLibwItems -ForegroundColor Green
    Write-Host "Total # of items: " $totalitems -ForegroundColor Green
    Write-Host "Total # of items in DocLib\Subfolders: " $subfolderitems -ForegroundColor Green
    $finishtime = Get-Date
    Write-Host
    Write-Host “Script Duration” –ForegroundColor Yellow
    Write-Host “Started: “ $starttime –ForegroundColor Yellow
    Write-Host “Finished: “ $finishtime –ForegroundColor Yellow
    Stop-SPAssignment -Global

  • SQL query to populate the records, the maximum processed should be less than 10 records per week.

    Dear All,
    I have a requirement, to write a SQL query to populate the records which are inserted less than 10 no of records.
    The tables has the cretaed_date column and along with other key column which will have unique values.
    Ex1:  The user might have inserted records from application, per week basis, between the date range '01-jun-2013' - 08-jun-2013  , the no of records created by the user during this week may be less than 10 records or more.
    But I want to populate the records by giving date range that too, it should pick the records the count which fall with in 10 records.
    I dont want the query to populate the records if the user has inserted more than 10 records in a week.
    Ex2:
    User 1 has created 15 records during the week 1 ( the query should not populate this ).
    User 2: has cretaed less than 10 records from the UI during the week 2. ( This details should get populated ).
    Thanks

    Use COUNT to find how many rows where inserted in a week.
    If this does not answer your question then please read Re: 2. How do I ask a question on the forums? And provide necessary details.

  • SQL query to get the Datetime 06 hours prior to the table Datetime value

    Hi Experts,
                    I'm just trying to create a SQL query to get the Datetime which should be 06 hours prior to my Table column value(Executiontime),
    Eg: my Executiontime(column) value is 07:00AM means, this query should fetch the detail of first VMName from table at 01:00AM, 
    SQL Table Name: TestTable
    Columns: VMName(varchar),status(varchar) Executiontime(Datetime)
    SQL Query : Select Top 1 VMName from
    TestTable where convert(date,Exeutiontime)=convert(date,getdate()) and
    status='0' and ExecutionTime > dateadd(hour,6,getdate())
    Request someone to alter this Query to my requirement or give me the new one.
    Regards,
    Sundar
    Sundar

    Hi All,
            Thanks for your Prompt response. I tried the below queries, but still I don't have any luck. Actually the queries are returning the value before the condition met (say when the time difference is more than 06 hours). I want the
    query to return exactly @ 06 hour difference or less than 06 hours,
    Query 01: Select Top 1 VMName from TestTable where
    convert(date,Exeutiontime)=convert(date,getdate())
    and status='0'
    and ExecutionTime >
    dateadd(hour,-6,getdate())
    Query 02: Select
    Top 1 VMName from TestTable where
    status='0'
    and ExecutionTime >
    dateadd(hour,-6,getdate())
    Query 03: Select
    Top 1 VMName from TestTable where status='0'
    and ExecutionTime >
    dateadd(hour,-6,ExecutionTime)
              Can someone point out the mistake please.
    Regards,
    Sundar
    Sundar

  • Sql query to achive the running division

    Hi all, plz help me out with the sql query to achive the below output
    create table emp_a (empno number, deptno number, sal number)
    insert into emp_a values(901, 10,100);
    insert into emp_a values(902, 10,400);
    insert into emp_a values(901, 20,300);
    insert into emp_a values(902, 20,2100);
    i want the ouput in below format
    empno deptno sal div_sal
    901 10 100 (300/100)
    901 20 300 (300/100)
    902 10 400 (2100/400)
    902 20 2100 (2100/400)
    the div_sal column should have the output of greatest sal/second smallest sal for each empno

    Hi,
    781649 wrote:
    Hi all, plz help me out with the sql query to achive the below output
    create table emp_a (empno number, deptno number, sal number)
    insert into emp_a values(901, 10,100);
    insert into emp_a values(902, 10,400);
    insert into emp_a values(901, 20,300);
    insert into emp_a values(902, 20,2100);
    i want the ouput in below format
    empno deptno sal div_sal
    901 10 100 (300/100)
    901 20 300 (300/100)
    902 10 400 (2100/400)
    902 20 2100 (2100/400)
    the div_sal column should have the output of greatest sal/second smallest sal for each empnofor empno=901, then second smallest sal is 300. For empno=902, the second smallest sal is 2100.
    Instead of "second *smallest* ", do you mean "second *greatest* "?
    What if there's a tie (e.g.
    INSERT INTO emp_a (empno, deptno, sal) VALUES (903, 10, 300);
    INSERT INTO emp_a (empno, deptno, sal) VALUES (903, 20, 300);
    INSERT INTO emp_a (empno, deptno, sal) VALUES (903, 30, 200);) Would you count 200 or 300 as the second greatest?
    Here's one way:
    WITH     got_r_num     AS
         SELECT     empno, deptno, sal
         ,     ROW_NUMBER () OVER ( PARTITION BY  empno
                                   ORDER BY          sal     DESC
                           )         AS r_num
         FROM    emp_a
    SELECT       e.empno
    ,       e.deptno
    ,       e.sal
    ,       '(' || TO_CHAR (r1.sal)
               || '/'
               || TO_CHAR (r2.sal)
               || ')'          AS div_sal
    FROM       emp_a           e
    JOIN       got_r_num     r1  ON      e.empno     = r1.empno
    JOIN       got_r_num     r2  ON   e.empno     = r2.empno
    WHERE       r1.r_num     = 1
    AND       r2.r_num     = 2
    ;

  • SQL query to get the list of approvals

    Hi,
    Could someone let me know the SQL query to get the list of all the pending approvals for a user in OIM 11g R2.
    Thanks

    There are a few ways to do this:
    -  The easiest would be to use a Relationship Query from the CMC. To do this, go to the Universes section on the CMC, right click on the relevant universe, select tools >> Check Relationships.
    - Use Query Builder. You will need more than one query to pull the information you need. You could try something like the below (for Webi)
    SELECT SI_NAME, SI_WEBI, SI_DATACONNECTION FROM CI_APPOBJECTS
    WHERE SI_KIND = 'universe' and SI_NAME = 'Universe Name'
    This will give you a list of Webi Reports by SI_ID.
    You'll need another query to list Webi report names:
    SELECT SI_NAME FROM CI_INFOOBJECTS WHERE SI_ID IN (SI_ID from query above)
    - This is trivial via Auditing / the Activity universe. This of course will only return reports that have already run.
    Best.
    Srinivas

  • Sql query to find the balances for a customer account wise.

    Hi,
    Could someone help me with the sql query to find the balances for each customer account wise. This is need to generate the report.
    presently we are using this query, but the output doesnot return the expected result.
    SELECT sum(nvl(ps.acctd_amount_due_remaining,0)) "Balance"
    FROM      ra_cust_trx_line_gl_dist_all gld,
              gl_code_combinations c,
              ar_payment_schedules_all ps,
              RA_CUSTOMER_TRX_ALL rat,
              ra_customers rc
    WHERE      c.CHART_OF_ACCOUNTS_ID = 101
    and gld.code_combination_id = c.code_combination_id
         and rat.CUSTOMER_TRX_ID=gld.CUSTOMER_TRX_ID
         and rat.CUSTOMER_TRX_ID=ps.CUSTOMER_TRX_ID
    and ps.customer_id=rc.customer_id
         and ps.status='OP'
         and ps.gl_date <= :PDATE
         and ps.org_id=:PORGID
         and ps.class in ('GUAR','INV','DM','DEP')
    and c.SEGMENT4=:Account_id
    and ps.customer_id=:Customer_id
    Thanks in advance.
    Kalyan.

    Can someone help us with this.

  • Can anybody provide the SQL query to find the files uploaded in a particular folder?

    Hi All,
    Can anybody provide the SQL query to find the documents (document name) uploaded in a particular folder? While clicking on folder in
    GUI I'm hitting the Timeout error. I would like to find the files uploaded into this folder from SQLPLUS.
    Any help is greatly appreciated.
    With best regards,
    Nevin

    Nevin,
    Be great if we could know the version of Portal. For Rel. 1, here's the query
    select id,masterthingid from wwv_things
    where siteid = &site
    and cornerid = &corner
    &site - Content Area id
    &corner - Folder id
    if you don't know the folder id, use
    select id from wwv_corners where siteid = &site
    and name = &folder
    Hope this helps. I have run into this situation before. Usually, the culprits were
    one of the following:
    1. Junk Characters in description of item (caused due to Copy-Paste)
    2. Special Characters in the File name
    Hi All,
    Can anybody provide the SQL query to find the documents (document name) uploaded in a particular folder? While clicking on folder in
    GUI I'm hitting the Timeout error. I would like to find the files uploaded into this folder from SQLPLUS.
    Any help is greatly appreciated.
    With best regards,
    Nevin

  • Sql Query to know the OS in which database is installed

    Hi,
    I want to know the OS in which my database is installed using SQL Query.
    Is it possible?
    Regards
    Salih KM

    SQL> select dbms_utility.port_string from dual;
    PORT_STRING
    IBM AIX64/RS6000 V4 - 8.1.0
    SQL> Nicolas.

  • Same the same query against all the schemas

    Hi all,I am a newbie to databases
    I have a requirement where in in need to run the same query against all the schema s in the database.what would be the best way to do it.other than logging into each user and running query.Its a complex query I can't do a direct select  from sys or other even for I will have to change a lot of things.Is there a easier way to do it ??
    Thanks in advance

    990051 wrote:
    Hi all,I am a newbie to databases
    I have a requirement where in in need to run the same query against all the schema s in the database.what would be the best way to do it.other than logging into each user and running query.Its a complex query I can't do a direct select  from sys or other even for I will have to change a lot of things.Is there a easier way to do it ??
    Thanks in advance
    you have a choice between logging into each user & running the SQL or you can log into each user & run the SQL.

Maybe you are looking for

  • How can I include a captivate variable in the URL of the website widget?

    I am using the website widget to bring up some customized content during the course. The URL contains a variable which will be different for every user. I can't find the option of including a variable in the URL with the widget. Has any figured out h

  • SAP History

    Hi everybody, I am learning XI but i am really interested how SAP developed overtime. Are there any documents in which I can read about the past products and their properties. Ex: R/1 : How does it started, what did it do, how it was developed, new f

  • Problem with starting Boot camp

    Hi all, when i try to use boot camp assistant(open boot camp assistant and click continue) it say 'you must update your system soft ware before using this setup assistant' evebn though I have updated by system using Software update option. Please hel

  • NOKIA PC SUITE'S LATEST VERSION INFORMATION - KIND...

    Hi Moderators, Please do check our forum says that latest Nokia PC Suite has 7.0 version released 2-Jul-2008 The latest version of Nokia PC Suite is 7.0, released 2-Jul-2008 - download it for free at www.nokia.com/pcsuite. Please do make change in ou

  • Can I download a trial version?

    I've never used Motion before, so I wanted to download a trial version before I bought... I'm still a student so $50 is a lot