我有一个复杂的查询,我已将其转储到临时表中。
在这个数据集中,我有不同类型的交易:电影,COD,功能,其他。
所有COD和其他交易以及10K和15K之间的总交易额应该总计为一行,交易名称为" TOTAL COD" 另外,它应该拥有它自己的路线。
我该怎么做?我无法使用{10}和15k之间的GROUP BY
来SUM(totalrev_YTD)
。
任何人都可以帮忙:
SELECT
location, locationid, dealtype,
(CASE
WHEN dealtype = 'OTHER (COD, ETC)' and totalrev_YTD BETWEEN 10000 AND 15000
THEN 'OTHER (COD, ETC)'
ELSE deal
END) as deal,
rental_PW, rental_MTD, rental_QTD, rental_YTD,
sales_PW, sales_MTD, sales_QTD, sales_YTD,
otherrev_PW, otherrev_MTD, otherrev_QTD, otherrev_YTD,
totalrev_PW, totalrev_MTD, totalrev_QTD, totalrev_YTD
FROM
#temp_rev t1
WHERE
dealtype = 'OTHER (COD, ETC)'
GROUP BY
(CASE
WHEN dealtype = 'OTHER (COD, ETC)' and totalrev_YTD BETWEEN 10000 AND 15000
THEN 'OTHER (COD, ETC)'
ELSE deal
END),
location, locationid, dealtype,
rental_PW, rental_MTD, rental_QTD, rental_YTD,
sales_PW, sales_MTD, sales_QTD, sales_YTD,
otherrev_PW, otherrev_MTD, otherrev_QTD, otherrev_YTD,
totalrev_PW, totalrev_MTD, totalrev_QTD, totalrev_YTD
这方面的一个例子是我有10个COD,其他交易。其中1笔交易有totalrev_YTD
> 15K。在这种情况下,它应该以自己的行显示,而另一个应该只是聚合。
答案 0 :(得分:0)
我认为你的GROUP BY
很好,你只需要它在较少的列上,然后你聚合(用SUM
)所有应该是,总和的数字。
在它是“单行”交易的情况下,查询将只对这一行求和,这是完全正常的。
示例:
SELECT location, locationid, dealtype
, (CASE WHEN dealtype = 'OTHER (COD, ETC)' and totalrev_YTD BETWEEN 10000 AND 15000 THEN 'OTHER (COD, ETC)'
ELSE deal
END
) as deal,
sum(rental_PW) as rental_PW,
sum(rental_MTD) as rental_MTD,
..., -- insert other summed columns here
sum(totalrev_YTD) as totalrev_YTD
FROM #temp_rev t1
WHERE dealtype ='OTHER (COD, ETC)'
GROUP BY
(CASE WHEN dealtype = 'OTHER (COD, ETC)' and totalrev_YTD BETWEEN 10000 AND 15000 THEN 'OTHER (COD, ETC)'
ELSE deal
END
) ,
location, locationid, dealtype