sum field twice in same query using different criteria

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aas4mis
    New Member
    • Jan 2008
    • 97

    sum field twice in same query using different criteria

    I have a table stating descriptions (desc) and quantities (qq). How would I go about getting the sum for all rugs [desc like "*rug*"] and the sum for all non rugs [desc not like "*rug*"] in the same query/subquery?
    Thanks in advance. This has been pushing my buttons for the last hour and a half.
  • Stewart Ross
    Recognized Expert Moderator Specialist
    • Feb 2008
    • 2545

    #2
    Hi. You can use two calculated fields using IIFs as shown below:

    Code:
    Select desc, sum(IIF(desc like "*rug*", [qq], 0)) as sum1, sum(IIF(desc not like "*rug*", [qq], 0) from Yourtable Group By Desc ... etc
    -Stewart
    Last edited by Stewart Ross; Aug 5 '08, 05:56 AM. Reason: corrected mistake in second IIF

    Comment

    • Stewart Ross
      Recognized Expert Moderator Specialist
      • Feb 2008
      • 2545

      #3
      Sorry, when I wrote the above reply I included the Desc field in the Select. You should NOT include it in your query, as to do so will stop the two computed fields from grouping on the partial matches which you need - just include the two computed fields on their own.

      -Stewart

      Comment

      • aas4mis
        New Member
        • Jan 2008
        • 97

        #4
        Originally posted by Stewart Ross Inverness
        Hi. You can use two calculated fields using IIFs as shown below:

        Code:
        Select desc, sum(IIF(desc like "*rug*", [qq], 0)) as sum1, sum(IIF(desc not like "*rug*", [qq], 0) from Yourtable Group By Desc ... etc
        -Stewart
        Beautiful. Thanks for the help, just what I was looking for. I was even able to reference both aliases and divide to get the percentage of rugs skipped.

        ** don't forget the ")" after the second IIF statement.

        Comment

        • NeoPa
          Recognized Expert Moderator MVP
          • Oct 2006
          • 32663

          #5
          Originally posted by aas4mis
          ...
          ** don't forget the ")" after the second IIF statement.
          You just can't get the staff nowadays :D

          Comment

          • aas4mis
            New Member
            • Jan 2008
            • 97

            #6
            Originally posted by NeoPa
            You just can't get the staff nowadays :D
            Ha! I think they do a fine job here on the access forum, from my experience this is the most active. Oh yeah.. good job with the new [C0DE] fields.. looks good.

            Comment

            Working...