Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Database & SysAdmin
  3. Database
  4. How to loop or something a temp distinct table to sum up the totals

How to loop or something a temp distinct table to sum up the totals

Scheduled Pinned Locked Moved Database
sql-serverdatabasesysadminhelptutorial
15 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Jorgen Andersson

    jkirkerx wrote:

    The thumbnail was just to show the picture of the item.

    Yes, but you're storing multiple instances of the same item which isn't very efficient when the database grows. It also gives you many records to update when you change the picture. Put it in a different table with an ID and join[^] it in to the base query

    jkirkerx wrote:

    Normally, i would just do the math in asp.net, but I thought I would expand my knowledge of SQL.

    In this case it's the right place to do it. SQL excels at storing, filtering and aggregation of data. So any math that comes with the aggregation belongs to the database (as a general but not specific rule, there are always exceptions).

    Wrong is evil and must be defeated. - Jeff Ello[^]

    J Offline
    J Offline
    jkirkerx
    wrote on last edited by
    #6

    That's close to exactly what I wanted. I had no idea that SQL was so, I'm not sure what word to use here, but in so few lines, it was able to produce the result I wanted. So the Group By Clause replaced the Distinct I was using to just produce to 2 items I wanted. Now I just need to add up the total Qty for each item. The SubTotal is correct, but the Qty is still just 1, should be like 7 for the first line. Let me see if I can solve this part myself. I may have a question Thanks!

    DECLARE @YearAS int;
    DECLARE @MonthAS int;
    DECLARE @DayAS int;
    SET @Year= 2013;
    SET @Month= 8;
    SET @Day= 29;

    DECLARE @startDate AS DATE;
    DECLARE @stopDate AS DATE;
    SET @startDate = DATETIMEFROMPARTS(@Year, @Month @Day 0, 0, 0, 0);
    SET @stopDate = DATETIMEFROMPARTS(@Year, @Month @Day 23, 59, 59, 999);
    DECLARE @SummaryItems TABLE(
    PartNumber VarChar(80),
    ThumbNail VarChar(250),
    SDescription VarChar(250),
    Qty INT,
    Cost Decimal,
    Price Decimal,
    SubTotal Decimal
    )
    INSERT INTO @SummaryItems (PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SubTotal)
    SELECT PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SUM(Qty * Price) From CompletedOrdersCart
    WHERE OrderDate > @startDate AND OrderDate < @stopDate
    GROUP BY PartNumber, Thumbnail, SDescription, Qty, Cost, Price
    SELECT PartNumber, Thumbnail, SDescription, Qty, Cost, Price, SubTotal FROM @SummaryItems;

    This is what I got returned, the Qty just needs to be 7, so 7 * 44.00 = 308.00

    PN, Thumbnail, Description, Qty, Cost, Price, SubTotal
    06-10, /Images/thumbnail/06-10.jpg, 10 inch Continuious Blade, 1, 22.00, 44.00, 308.00

    FYI: I tried between, but I would of had to deduct a day, and add a day for start and stop.

    C J 2 Replies Last reply
    0
    • J jkirkerx

      That's close to exactly what I wanted. I had no idea that SQL was so, I'm not sure what word to use here, but in so few lines, it was able to produce the result I wanted. So the Group By Clause replaced the Distinct I was using to just produce to 2 items I wanted. Now I just need to add up the total Qty for each item. The SubTotal is correct, but the Qty is still just 1, should be like 7 for the first line. Let me see if I can solve this part myself. I may have a question Thanks!

      DECLARE @YearAS int;
      DECLARE @MonthAS int;
      DECLARE @DayAS int;
      SET @Year= 2013;
      SET @Month= 8;
      SET @Day= 29;

      DECLARE @startDate AS DATE;
      DECLARE @stopDate AS DATE;
      SET @startDate = DATETIMEFROMPARTS(@Year, @Month @Day 0, 0, 0, 0);
      SET @stopDate = DATETIMEFROMPARTS(@Year, @Month @Day 23, 59, 59, 999);
      DECLARE @SummaryItems TABLE(
      PartNumber VarChar(80),
      ThumbNail VarChar(250),
      SDescription VarChar(250),
      Qty INT,
      Cost Decimal,
      Price Decimal,
      SubTotal Decimal
      )
      INSERT INTO @SummaryItems (PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SubTotal)
      SELECT PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SUM(Qty * Price) From CompletedOrdersCart
      WHERE OrderDate > @startDate AND OrderDate < @stopDate
      GROUP BY PartNumber, Thumbnail, SDescription, Qty, Cost, Price
      SELECT PartNumber, Thumbnail, SDescription, Qty, Cost, Price, SubTotal FROM @SummaryItems;

      This is what I got returned, the Qty just needs to be 7, so 7 * 44.00 = 308.00

      PN, Thumbnail, Description, Qty, Cost, Price, SubTotal
      06-10, /Images/thumbnail/06-10.jpg, 10 inch Continuious Blade, 1, 22.00, 44.00, 308.00

      FYI: I tried between, but I would of had to deduct a day, and add a day for start and stop.

      C Offline
      C Offline
      Christian Graus
      wrote on last edited by
      #7

      Where does the QTY come from, and why should it be 7 ? if it's the result of a different group by, you can get it with a CTE[^], and then join it back in to your query. CTEs are useful when you need to return two calculated values based on different group by statements.

      Christian Graus My new article series is all about SQL !!!

      J J 2 Replies Last reply
      0
      • J jkirkerx

        That's close to exactly what I wanted. I had no idea that SQL was so, I'm not sure what word to use here, but in so few lines, it was able to produce the result I wanted. So the Group By Clause replaced the Distinct I was using to just produce to 2 items I wanted. Now I just need to add up the total Qty for each item. The SubTotal is correct, but the Qty is still just 1, should be like 7 for the first line. Let me see if I can solve this part myself. I may have a question Thanks!

        DECLARE @YearAS int;
        DECLARE @MonthAS int;
        DECLARE @DayAS int;
        SET @Year= 2013;
        SET @Month= 8;
        SET @Day= 29;

        DECLARE @startDate AS DATE;
        DECLARE @stopDate AS DATE;
        SET @startDate = DATETIMEFROMPARTS(@Year, @Month @Day 0, 0, 0, 0);
        SET @stopDate = DATETIMEFROMPARTS(@Year, @Month @Day 23, 59, 59, 999);
        DECLARE @SummaryItems TABLE(
        PartNumber VarChar(80),
        ThumbNail VarChar(250),
        SDescription VarChar(250),
        Qty INT,
        Cost Decimal,
        Price Decimal,
        SubTotal Decimal
        )
        INSERT INTO @SummaryItems (PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SubTotal)
        SELECT PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SUM(Qty * Price) From CompletedOrdersCart
        WHERE OrderDate > @startDate AND OrderDate < @stopDate
        GROUP BY PartNumber, Thumbnail, SDescription, Qty, Cost, Price
        SELECT PartNumber, Thumbnail, SDescription, Qty, Cost, Price, SubTotal FROM @SummaryItems;

        This is what I got returned, the Qty just needs to be 7, so 7 * 44.00 = 308.00

        PN, Thumbnail, Description, Qty, Cost, Price, SubTotal
        06-10, /Images/thumbnail/06-10.jpg, 10 inch Continuious Blade, 1, 22.00, 44.00, 308.00

        FYI: I tried between, but I would of had to deduct a day, and add a day for start and stop.

        J Offline
        J Offline
        Jorgen Andersson
        wrote on last edited by
        #8

        I believe you can remove also the last temptable:

        DECLARE @YearAS int;
        DECLARE @MonthAS int;
        DECLARE @DayAS int;
        SET @Year= 2013;
        SET @Month= 8;
        SET @Day= 29;

        DECLARE @startDate AS DATE;
        DECLARE @stopDate AS DATE;
        SET @startDate = DATETIMEFROMPARTS(@Year, @Month @Day 0, 0, 0, 0);
        SET @stopDate = DATETIMEFROMPARTS(@Year, @Month @Day 23, 59, 59, 999);

        SELECT PartNumber, ThumbNail, SDescription, sum(Qty) Qty, Cost, Price, SUM(Qty * Price) SubTotal From CompletedOrdersCart
        WHERE OrderDate > @startDate AND OrderDate < @stopDate
        GROUP BY PartNumber, Thumbnail, SDescription, Cost, Price

        And just like the thumbnail, the SDescription belongs in a different table, for the same reasons

        jkirkerx wrote:

        I tried between, but I would of had to deduct a day, and add a day for start and stop.

        My bad,

        WHERE OrderDate BETWEEN @StartDate AND @StopDate

        is the same as

        WHERE OrderDate >= @startDate AND OrderDate <= @stopDate

        not

        WHERE OrderDate > @startDate AND OrderDate < @stopDate

        Wrong is evil and must be defeated. - Jeff Ello[^]

        J 2 Replies Last reply
        0
        • C Christian Graus

          Where does the QTY come from, and why should it be 7 ? if it's the result of a different group by, you can get it with a CTE[^], and then join it back in to your query. CTEs are useful when you need to return two calculated values based on different group by statements.

          Christian Graus My new article series is all about SQL !!!

          J Offline
          J Offline
          Jorgen Andersson
          wrote on last edited by
          #9

          The partnumber and thumbnail has changed since the original post, I believe you can safely assume the database contents or some other circumstances has also changed.

          Wrong is evil and must be defeated. - Jeff Ello[^]

          1 Reply Last reply
          0
          • C Christian Graus

            Where does the QTY come from, and why should it be 7 ? if it's the result of a different group by, you can get it with a CTE[^], and then join it back in to your query. CTEs are useful when you need to return two calculated values based on different group by statements.

            Christian Graus My new article series is all about SQL !!!

            J Offline
            J Offline
            jkirkerx
            wrote on last edited by
            #10

            The Qty comes from like a shopping cart history table. So all cart items sold on the requested report date may contain 20 orders for the same item, so that day, 7 people ordered the same item of qty 1, so the qty would be 7. 7 was the result I was looking for to make sure the math was right. My explanation below is crude, but it should represent the thought. I have this bad feeling about this, I think your going to rip me a new one here ;P

            Shopping Cart History
            date ------- PN ---------- Qty
            08/29/2013 - 8AM 06-CR10 1
            08/29/2013 - 9AM 06-CR10 1
            08/29/2013 - 10AM 06-CR10 1
            08/29/2013 - 11AM 12-ZZZ1 2
            So the Qty would be 3

            the result set would be

            Items requiring fulfillment today
            PN --------Qty
            06-CR10 3
            12-ZZZ1 2

            1 Reply Last reply
            0
            • J Jorgen Andersson

              I believe you can remove also the last temptable:

              DECLARE @YearAS int;
              DECLARE @MonthAS int;
              DECLARE @DayAS int;
              SET @Year= 2013;
              SET @Month= 8;
              SET @Day= 29;

              DECLARE @startDate AS DATE;
              DECLARE @stopDate AS DATE;
              SET @startDate = DATETIMEFROMPARTS(@Year, @Month @Day 0, 0, 0, 0);
              SET @stopDate = DATETIMEFROMPARTS(@Year, @Month @Day 23, 59, 59, 999);

              SELECT PartNumber, ThumbNail, SDescription, sum(Qty) Qty, Cost, Price, SUM(Qty * Price) SubTotal From CompletedOrdersCart
              WHERE OrderDate > @startDate AND OrderDate < @stopDate
              GROUP BY PartNumber, Thumbnail, SDescription, Cost, Price

              And just like the thumbnail, the SDescription belongs in a different table, for the same reasons

              jkirkerx wrote:

              I tried between, but I would of had to deduct a day, and add a day for start and stop.

              My bad,

              WHERE OrderDate BETWEEN @StartDate AND @StopDate

              is the same as

              WHERE OrderDate >= @startDate AND OrderDate <= @stopDate

              not

              WHERE OrderDate > @startDate AND OrderDate < @stopDate

              Wrong is evil and must be defeated. - Jeff Ello[^]

              J Offline
              J Offline
              jkirkerx
              wrote on last edited by
              #11

              I think I ended up doing that, and was amazed at how it worked. Let me check, This is the SQL in the asp.net function I used for testing. I kept the DateTimeFromParts because I stored the order date as a timestamp, and not a date, and had to be more precise with the hours minutes and seconds. I was originally BETWEEN, but I could not get a result, and it took me hours to figure it out, plus I had upgraded to SQL Server 2012 at the time. Then the timestamp dawned on me, and I spent another hour figuring out how to be more precise. I'd rather use between, and not use anything specific to 2012. I SUM the Qty to get 7, and it worked on the test data set, not sure if I was just lucky to get that value, I need to find more data on different days to fully check it.

              "DECLARE @startDate AS DATE; " & _
              "DECLARE @stopDate AS DATE; " & _
              "SET @startDate = DATETIMEFROMPARTS(@Year, @Month, @Day, 0, 0, 0, 0); " & _
              "SET @stopDate = DATETIMEFROMPARTS(@Year, @Month, @Day, 23, 59, 59, 999); " & _
              "DECLARE @SummaryItems TABLE(" & _
              "PartNumber VarChar(80), " & _
              "ThumbNail VarChar(250), " & _
              "SDescription VarChar(250), " & _
              "Qty INT, " & _
              "Cost Decimal, " & _
              "Price Decimal, " & _
              "SubTotal Decimal " & _
              ") " & _
              "INSERT INTO @SummaryItems (PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SubTotal) " & _
              "SELECT PartNumber, ThumbNail, SDescription, SUM(Qty), Cost, Price, SUM(Qty * Price) From CompletedOrdersCart " & _
              "WHERE OrderDate > @startDate AND OrderDate < @stopDate " & _
              "GROUP BY PartNumber, Thumbnail, SDescription, Qty, Cost, Price " & _
              "SELECT PartNumber, Thumbnail, SDescription, Qty, Cost, Price, SubTotal FROM @SummaryItems;"

              J 1 Reply Last reply
              0
              • J Jorgen Andersson

                I believe you can remove also the last temptable:

                DECLARE @YearAS int;
                DECLARE @MonthAS int;
                DECLARE @DayAS int;
                SET @Year= 2013;
                SET @Month= 8;
                SET @Day= 29;

                DECLARE @startDate AS DATE;
                DECLARE @stopDate AS DATE;
                SET @startDate = DATETIMEFROMPARTS(@Year, @Month @Day 0, 0, 0, 0);
                SET @stopDate = DATETIMEFROMPARTS(@Year, @Month @Day 23, 59, 59, 999);

                SELECT PartNumber, ThumbNail, SDescription, sum(Qty) Qty, Cost, Price, SUM(Qty * Price) SubTotal From CompletedOrdersCart
                WHERE OrderDate > @startDate AND OrderDate < @stopDate
                GROUP BY PartNumber, Thumbnail, SDescription, Cost, Price

                And just like the thumbnail, the SDescription belongs in a different table, for the same reasons

                jkirkerx wrote:

                I tried between, but I would of had to deduct a day, and add a day for start and stop.

                My bad,

                WHERE OrderDate BETWEEN @StartDate AND @StopDate

                is the same as

                WHERE OrderDate >= @startDate AND OrderDate <= @stopDate

                not

                WHERE OrderDate > @startDate AND OrderDate < @stopDate

                Wrong is evil and must be defeated. - Jeff Ello[^]

                J Offline
                J Offline
                jkirkerx
                wrote on last edited by
                #12

                Click! Oh, I see now what your saying. If the Thumbnail image is changed during the day, I can end up with 2 thumbnail image locations in a dataset. So which one would be right. I'm open to error with my SQL, and it will back fire on me soon, because it's history data. So I should get rid of the thumbnail, and make a different request for that data. That's why I should store the image data in another table, and use a join. I never thought of that. That could take me a week to change in the entire program, but it must be done. Slap me in the back of the head.

                J 1 Reply Last reply
                0
                • J jkirkerx

                  I think I ended up doing that, and was amazed at how it worked. Let me check, This is the SQL in the asp.net function I used for testing. I kept the DateTimeFromParts because I stored the order date as a timestamp, and not a date, and had to be more precise with the hours minutes and seconds. I was originally BETWEEN, but I could not get a result, and it took me hours to figure it out, plus I had upgraded to SQL Server 2012 at the time. Then the timestamp dawned on me, and I spent another hour figuring out how to be more precise. I'd rather use between, and not use anything specific to 2012. I SUM the Qty to get 7, and it worked on the test data set, not sure if I was just lucky to get that value, I need to find more data on different days to fully check it.

                  "DECLARE @startDate AS DATE; " & _
                  "DECLARE @stopDate AS DATE; " & _
                  "SET @startDate = DATETIMEFROMPARTS(@Year, @Month, @Day, 0, 0, 0, 0); " & _
                  "SET @stopDate = DATETIMEFROMPARTS(@Year, @Month, @Day, 23, 59, 59, 999); " & _
                  "DECLARE @SummaryItems TABLE(" & _
                  "PartNumber VarChar(80), " & _
                  "ThumbNail VarChar(250), " & _
                  "SDescription VarChar(250), " & _
                  "Qty INT, " & _
                  "Cost Decimal, " & _
                  "Price Decimal, " & _
                  "SubTotal Decimal " & _
                  ") " & _
                  "INSERT INTO @SummaryItems (PartNumber, ThumbNail, SDescription, Qty, Cost, Price, SubTotal) " & _
                  "SELECT PartNumber, ThumbNail, SDescription, SUM(Qty), Cost, Price, SUM(Qty * Price) From CompletedOrdersCart " & _
                  "WHERE OrderDate > @startDate AND OrderDate < @stopDate " & _
                  "GROUP BY PartNumber, Thumbnail, SDescription, Qty, Cost, Price " & _
                  "SELECT PartNumber, Thumbnail, SDescription, Qty, Cost, Price, SubTotal FROM @SummaryItems;"

                  J Offline
                  J Offline
                  Jorgen Andersson
                  wrote on last edited by
                  #13

                  You need to remove Qty from the GROUP BY or you might get "unexpected" results. And I believe you can also skip @SummaryItems. It doesn't serve any purpose.

                  Wrong is evil and must be defeated. - Jeff Ello[^]

                  1 Reply Last reply
                  0
                  • J jkirkerx

                    Click! Oh, I see now what your saying. If the Thumbnail image is changed during the day, I can end up with 2 thumbnail image locations in a dataset. So which one would be right. I'm open to error with my SQL, and it will back fire on me soon, because it's history data. So I should get rid of the thumbnail, and make a different request for that data. That's why I should store the image data in another table, and use a join. I never thought of that. That could take me a week to change in the entire program, but it must be done. Slap me in the back of the head.

                    J Offline
                    J Offline
                    Jorgen Andersson
                    wrote on last edited by
                    #14

                    It's called normalization, and we have all walked that way. While the explanations for Normalization in Wikipedia[^] is pretty good. I personally recommend one[^] made by Peso (a bit of a legend on a different forum), because he's explaining by example.

                    Wrong is evil and must be defeated. - Jeff Ello[^]

                    J 1 Reply Last reply
                    0
                    • J Jorgen Andersson

                      It's called normalization, and we have all walked that way. While the explanations for Normalization in Wikipedia[^] is pretty good. I personally recommend one[^] made by Peso (a bit of a legend on a different forum), because he's explaining by example.

                      Wrong is evil and must be defeated. - Jeff Ello[^]

                      J Offline
                      J Offline
                      jkirkerx
                      wrote on last edited by
                      #15

                      Wow Thanks for the optimization tips! I do need to expand my knowledge here and use the tools right. I'll play around with the TSQL in SQL Manager to see the various results and read the lessons. The temp table was cool to know, but if it can be done without it, then better.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups