I need to build a report to show per each product (obj_id) number of sales ( a
simple COUNT will do), total income
from the sales and number of units sold
(quantity). The following works OK, but I use DISTINCT and don't feel
comfortable
with future performance.
WITH myMainTable AS
(SELECT 1 AS obj_id, 'A'
AS obj_desc
UNION ALL
SELECT 2,'B'
UNION ALL
SELECT 3,'C'
UNION
ALL
SELECT 4,'D'
UNION ALL
SELECT 5,'E'
UNION ALL
SELECT
6,'F'),
myDataTable AS (
SELECT 1 AS obj_id,
3 AS qnty,
45 AS
total_price
UNION ALL
SELECT 1,4,87
UNION ALL
SELECT
1,1,10
UNION ALL
SELECT 1,40,751
UNION ALL
SELECT 2,10,8
UNION
ALL
SELECT 2,100,87
UNION ALL
SELECT 3,6,9)
SELECT DISTINCT
m.obj_id,
m.obj_desc,
SUM (d.total_price) OVER (PARTITION BY m.obj_id)
AS total_income,
SUM (d.qnty) OVER (PARTITION BY m.obj_id) AS
total_qnty,
COUNT(d.obj_id) OVER (PARTITION BY m.obj_id) AS
total_sales
FROM myMainTable m
JOIN myDataTable d
ON d.obj_id =
m.obj_id
simple COUNT will do), total income
from the sales and number of units sold
(quantity). The following works OK, but I use DISTINCT and don't feel
comfortable
with future performance.
WITH myMainTable AS
(SELECT 1 AS obj_id, 'A'
AS obj_desc
UNION ALL
SELECT 2,'B'
UNION ALL
SELECT 3,'C'
UNION
ALL
SELECT 4,'D'
UNION ALL
SELECT 5,'E'
UNION ALL
SELECT
6,'F'),
myDataTable AS (
SELECT 1 AS obj_id,
3 AS qnty,
45 AS
total_price
UNION ALL
SELECT 1,4,87
UNION ALL
SELECT
1,1,10
UNION ALL
SELECT 1,40,751
UNION ALL
SELECT 2,10,8
UNION
ALL
SELECT 2,100,87
UNION ALL
SELECT 3,6,9)
SELECT DISTINCT
m.obj_id,
m.obj_desc,
SUM (d.total_price) OVER (PARTITION BY m.obj_id)
AS total_income,
SUM (d.qnty) OVER (PARTITION BY m.obj_id) AS
total_qnty,
COUNT(d.obj_id) OVER (PARTITION BY m.obj_id) AS
total_sales
FROM myMainTable m
JOIN myDataTable d
ON d.obj_id =
m.obj_id