Ситуация:
Я хотел бы использовать Rollup
в конце моего вывода, но, кажется, добавляю одно и то же число несколько раз, следовательно, увеличивая общую сумму.
Мой запрос выглядит так:
; with cte as (
SELECT
cast(point.date as date) AS target_date
, 'all' AS [site]
, 'pc' AS device
, point.id
, point.category
, point.command
, staff
, point.point
FROM table.banana AS point
LEFT JOIN table.orange AS staff ON point.id=staff.id
WHERE
CAST(point.date AS date) = '2019-05-26'
)
-- base query
SELECT
base.target_date
, base.[site]
, base.device
, SUM(case when cte.category = 'Bonus'
and cte.type = 'free'
and cte.command = 'add'
and cte.staff is null then cte.point else 0 end) as total
FROM ( -- this is just a mapping
SELECT
(SELECT CAST(key_value AS DATE) FROM baseDate WHERE [KEY_NAME] = 'target_date') AS target_date
, [target].[site]
, [target].[device]
FROM (
SELECT 'net' AS [site], 'pc' AS device
UNION ALL SELECT 'net','android_app'
UNION ALL SELECT 'com','pc'
UNION ALL SELECT 'com','android_app'
) AS [target]) AS base
LEFT JOIN cte
ON base.target_date = cte.target_date
AND base.device = cte.device
GROUP BY
base.target_date
, base.[site]
, base.device
WITH ROLLUP
GO
Мой вывод:
+-------------+------+-------------+----------------------------+
| target_date | site | device | total |
+-------------+------+-------------+----------------------------+
| 5/26/2019 | com | android_app | - |
| 5/26/2019 | com | pc | 200,000.00 |
| 5/26/2019 | com | NULL | 200,000.00 |
| 5/26/2019 | net | android_app | - |
| 5/26/2019 | net | pc | 200,000.00 |
| 5/26/2019 | net | NULL | 200,000.00 |
| 5/26/2019 | NULL | NULL | 400,000.00 |
| NULL | NULL | NULL | 400,000.00 |
+-------------+------+-------------+----------------------------+
Мойожидаемый результат должен быть: Обратите внимание, что структура выглядит так, потому что у меня есть 10 других представлений, которые я должен присоединить к моему базовому запросу.
+-------------+------+-------------+----------------------------+
| target_date | site | device | total |
+-------------+------+-------------+----------------------------+
| 5/26/2019 | com | android_app | - |
| 5/26/2019 | com | pc | 200,000.00 |
| 5/26/2019 | com | NULL | 200,000.00 |
| 5/26/2019 | net | android_app | - |
| 5/26/2019 | net | pc | 200,000.00 |
| 5/26/2019 | net | NULL | 200,000.00 |
| 5/26/2019 | NULL | NULL | 200,000.00 |
| NULL | NULL | NULL | 200,000.00 |
+-------------+------+-------------+----------------------------+