简体   繁体   中英

In an SQL join operation, how to get the rows from the left join and only the aggregate of two columns from the right table

I am trying to SUM the quantity in tpos table and count the distinct number of stores for each item that is in tpos.

For each row in inv_dtl there could be mulitple rows in tpos tables. I would like to put a script together that would give me all the rows from the inv_dtl table and add two aggregate columns sum(tpos.quantiy), count(distinct, tpos.store_number) that matches the join condition.

Here is what I have so far. The aggregates are working but my output contains the number or rows that match in tpos.

For example 1 row in inv_dtl could have 100 rows in tpos. My output should contain 1 row plus the two aggregate columns but my current script generates 100 rows.

WITH FT1 As
(
  SELECT * FROM inv_dtl WHERE inv_no IN (16084, 23456, 14789)
),
FT2 As
(
  SELECT 
    FT1.*,
    SUM(tpos.quantity) OVER (partition by tpos.item_id) As pos_qty,
    DENSE_RANK() OVER (partition by tpos.store_number ORDER BY tpos.item_id ASC) +
    DENSE_RANK() OVER (partition by tpos.store_number ORDER BY tpos.item_id DESC)
      As unique_store_cnt
    FROM FT1
  LEFT JOIN tpos
    ON tpos.item_id = FT1.ITEM_ID
       And tpos.movement_date Between FT1.SDATE And FT1.EDATE
       And tpos.store_number != 'CMPNY'
)
SELECT * FROM FT2 ORDER BY ITEM_ID

Just use a conventional GROUP BY which will reduce the number of rows. But as I have no idea what columns you want from the first mentioned table so I have just invented 4 as an example.

WITH
      FT1 AS (
                  SELECT
                        col1, col2, col3, col4
                  FROM inv_dtl
                  WHERE inv_no IN (16084, 23456, 14789)
            ),
      FT3 AS (
                  SELECT
                        FT1.col1, FT1.col2, FT1.col3, FT1.col4
                      , SUM(tpos.quantity) OVER (PARTITION BY tpos.item_id) AS pos_qty
                      , ROW_NUMBER() OVER (PARTITION BY col1, col2, col3, col4 ASC) +
                        AS unique_store_cnt
                  FROM FT1
                  LEFT JOIN tpos ON tpos.item_id = FT1.ITEM_ID
                        AND tpos.movement_date BETWEEN FT1.SDATE AND FT1.EDATE
                        AND tpos.store_number != 'CMPNY'
                  GROUP BY
                        FT1.col1, FT1.col2, FT1.col3, FT1.col4
            )
SELECT
      *
FROM FT3
ORDER BY col1, col2, col3, col4

Do pleae note that RANK() and DENSE_RANK() can repeat numbers if data is of "equal rank". To guarantee a unique integer per row use ROW_NUMBER() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM