0

我有一个简单的表查询显示:

salesAreaId areaDescription Total
----------- --------------- -----------
N1          North           5
SE8         Southeast       3
SW7         Southwest       2
NE6         Northeast       2
NW5         Northwest       1
S3          South           1
W4          West            1
E2          East            1

(8 row(s) affected)

这是我的代码

SELECT st.salesAreaId, areaDescription,  
    COUNT(*) as Total
FROM store as st, salesArea as sa
WHERE st.salesAreaId = sa.salesAreaId
GROUP BY st.salesAreaId, areaDescription
ORDER BY 3 DESC
GO

我的问题是如何使用 COMPUTE 在总列下方添加总计行,我被教导在 ORDER BY 之后使用 COMPUTE

我不想使用 ROLLUP,我是否需要某种内部 SELECT 才能单独使用 Total。我读到的每个示例都说要像这样在 SUM 旁边键入列名

有什么建议么?

4

1 回答 1

1

试试这个:

SELECT st.salesAreaId, areaDescription,  
COUNT(*) as Total
FROM store as st, salesArea as sa
WHERE st.salesAreaId = sa.salesAreaId
GROUP BY st.salesAreaId, areaDescription
--order by would go here if needed - ordering by a constant won't have any effect though, so I've removed it from the statment
compute sum(count(*))

您可以将 sum 替换为任何聚合函数。我已经使用 count(*) 作为你正在做的事情,因为你将它用于你的小计 - 但你可以用一个列名/任何需要的东西来替换它。

附言。查看您的数据,您似乎可能在每个区域的小计之后?如果是这样,试试这个:

SELECT st.salesAreaId
, areaDescription
, COUNT(*) as Total
FROM store as st
inner join salesArea as sa
on st.salesAreaId = sa.salesAreaId
GROUP BY st.salesAreaId, areaDescription
ORDER BY st.salesAreaId, areaDescription
COMPUTE sum(count(*)) BY areaDescription
于 2012-11-24T01:09:27.770 回答