Search code examples
sqlsummary

Query is summing values multiple times


Hi my query below is summing multiple values based on @cropseasons in my table. Since i have 4 crop seasons it seems to be multiplying the values by 4 since i have crop season as 1, 2, 3 or 4. All i want is values for 1 crop season. Can anyone assist? I have crop season in both tables.

With Summary as (
    Select B_NAME as Branch, LOC as Location
          ,SUM(payment) as Gallons
          ,SUM(case when printed = 1 THEN Fee ELSE NULL END) as FeeCollected
          ,SUM(case when printed = 0 THEN Fee ELSE NULL END) as FeeNotCollected
          ,SUM(case when printed = 1 THEN Payment ELSE NULL END) as GallonsIssued
          ,SUM(case when printed = 0 THEN Payment ELSE NULL END) as GallonsNotIssued
    From SicbWeeklyDeliveriesFuelArchive F Inner Join FarmerGroups G ON G.BSI_CODE = F.BSI_CODE

    Where F.CROP_SEASON = @cropseason

    Group By B_NAME, LOC
    )

SELECT Branch
      ,Location
      ,Gallons
      ,GallonsIssued
      ,GallonsNotIssued
      ,FeeCollected
      ,FeeNotCollected
      ,((GallonsIssued/Gallons) * 100) as pct_GallonsCollected
    FROM Summary
    Order by Location, Branch

SicbWeeklyDeliveriesFuelArchive

+-------+----------+-------------+-----+---------+------+-------------+---------+
|  ID   | BSI_CODE |   B_NAME    | LOC | PAYMENT | FEE  | CROP_SEASON | PRINTED |
+-------+----------+-------------+-----+---------+------+-------------+---------+
| 18735 |     2176 | SAN NARCISO | CZ  |      85 |  8.5 |           4 |       0 |
| 18738 |     2176 | SAN NARCISO | CZ  |      65 |  6.5 |           4 |       0 |
| 18739 |    10494 | SAN NARCISO | CZ  |      85 |  8.5 |           3 |       0 |
+-------+----------+-------------+-----+---------+------+-------------+---------+

FarmerGroups

+-------+----------+-------------+-------------+
|  ID   | BSI_CODE | CROP_SEASON |   BRANCH    |
+-------+----------+-------------+-------------+
| 10473 |     2176 |           4 | SAN NARCISO |
| 11478 |     2176 |           3 | SAN NARCISO |
| 12787 |    10494 |           4 | SAN ROMAN   |
+-------+----------+-------------+-------------+

Solution

  • It seems your join criteria is incomplete. The tables share BSI_CODE and CROP_SEASON, so I guess you want:

    FROM sicbweeklydeliveriesfuelarchive f 
    JOIN farmergroups g ON g.bsi_code = f.bsi_code AND g.crop_season = f.crop_season
    WHERE f.crop_season = @cropseason
    

    But that's just guessing. Only you know how the tables are really related, what their rows represent, what columns make a row unique and what result you are actually after. Why do you join farmergroups at all? It looks like you are not really using the table in your query.