7

我在报表设计器中有一个这样的表:

Category:       1     2       3      4   Total
Max Amount:     x     y       z      c     ?

我需要获取 Max Amount 的总数,但表达式不允许我取 Sum(Max(amount)),并且此单元格的加总功能被禁用。

最大数量行是一个表达式,它采用每个类别的最大值。源数据有重复值,所以我只取最大值。例如:

Category    Amount
    1         4.6
    1         4.6
    1         4.6
    2          5
    3          4

表中的其他列不同,但数量相同,因此我不能只选择不同的值。

4

3 回答 3

10

也许是这样的:

SELECT
    SUM(t1.maxAmout)
FROM
(
    SELECT
        MAX(t.Amout) AS maxAmout,
        t.Category
    FROM
        yourTable AS t
    GROUP BY
        t.Category
) AS t1

你也可以这样做。如果您使用的是 sql server 2005+:

SELECT
    pvt.[1],
    pvt.[2],
    pvt.[3],
    (
        pvt.[1]+
        pvt.[2]+
        pvt.[3]
    ) AS Total
FROM
(
    SELECT
        t.Category,
        t.Amout
    FROM
        yourTable AS t
) AS SourceTable
PIVOT
(
    MAX(Amout)
    FOR Category IN([1],[2],[3])
) AS pvt

编辑

如果您有 1000 个类别。那么动态支点将是最好的解决方案。所以像这样:

测试数据

CREATE TABLE #T
    (
        Category INT,
        Amout FLOAT
    )

INSERT INTO #T
VALUES
    (1,4.6),
    (1,4.6),
    (1,4.6),
    (2,5),
    (3,4)

唯一的列名

DECLARE @cols VARCHAR(MAX)
DECLARE @colsTotal VARCHAR(MAX)
;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY t.Category ORDER BY t.Amout) AS RowNbr,
        t.*
    FROM
        #T AS t
)
SELECT  @cols = COALESCE(@cols + ','+QUOTENAME(Category),
                     QUOTENAME(Category)),
        @colsTotal=COALESCE(@colsTotal + '+ISNULL('+QUOTENAME(Category)+',0)',
                     'ISNULL('+QUOTENAME(Category)+',0)')
FROM 
    CTE
WHERE
    CTE.RowNbr=1
ORDER BY 
    Category

动态枢轴

DECLARE @query NVARCHAR(4000)=
N'SELECT
    '+@cols+',
    (
        '+@colsTotal+'
    ) AS Total
FROM
(
    SELECT
        t.Category,
        t.Amout
    FROM
        #T AS t
) AS SourceTable
PIVOT
(
    MAX(Amout)
    FOR Category IN('+@cols+')
) AS pvt'

EXECUTE(@query)
于 2012-04-19T14:39:10.727 回答
2
WITH
  aggregate
AS
(
  SELECT
    category,
    MAX(amount)  AS max_amount
  FROM
    yourTable
  GROUP BY
    category
)
SELECT
  MAX(CASE WHEN category = 1 THEN max_amount ELSE NULL END)    AS [1],
  MAX(CASE WHEN category = 2 THEN max_amount ELSE NULL END)    AS [2],
  MAX(CASE WHEN category = 3 THEN max_amount ELSE NULL END)    AS [3],
  MAX(CASE WHEN category = 4 THEN max_amount ELSE NULL END)    AS [4],
  SUM(max_amount)                                              AS [total]
FROM
  aggregate
于 2012-04-19T14:39:41.503 回答
0

以下返回单个值:

SELECT DISTINCT SUM(MAX(Amount)) OVER ()
FROM atable
GROUP BY Category

您可以将其用作计算Total列值的子查询。

或者,TOP (1)可以用来代替DISTINCT(不知道为什么我以前想不到):

SELECT TOP (1) SUM(MAX(Amount)) OVER ()
FROM atable
GROUP BY Category
于 2012-04-20T14:29:28.433 回答