1

我有一个问题让我困惑了 2 天。这是问题所在。我有一个看起来像这样的表:

在此处输入图像描述

我想做的是必须对最终出现在同一张表中的分组。对于上面的示例,我最终会得到以下结果:

在此处输入图像描述

这样的事情可以实现吗?如您所见,我们按不同的列进行分组。这不必通过一个查询来完成,但是,它必须以一个表/数据集结束。

4

3 回答 3

2

我会独立总结每个集合,然后使用 a 连接在一起full outer join,因为看起来你可能有多年的销售,但没有多年的收入,反之亦然......

SELECT
    ISNULL(PeriodEarnedYear, [Sale Year]) AS [Year],
    Earned,
    Sale
FROM
(
    SELECT
        PeriodEarnedYear,
        SUM(PeriodEarned) AS Earned
    FROM YourTable
    GROUP BY PeriodEarnedYear
) p FULL OUTER JOIN
(
    SELECT
        [Sale Year],
        SUM(Sale) AS Sale
    FROM YourTable
    GROUP BY [Sale Year]
) s ON p.PeriodEarnedYear = s.[Sale Year]
于 2012-11-08T17:49:29.843 回答
0

好像你需要这个:

select PeriodEarnedYear,
    sum(PeriodEarned) Earned,
    Sale
from yourtable
group by PeriodEarnedYear, Sale
于 2012-11-08T17:47:15.743 回答
0
SELECT SaleYear year, 
  0 earned, 
  sum(Sale) sale
FROM yourtable
group by saleyear
UNION
Select PeriodEarnedYear,
    sum(PeriodEarned) Earned,
    Sale
from yourtable
group by PeriodEarnedYear

但这做了一些假设。

于 2012-11-08T17:53:56.717 回答