TSQL组基于同一Recordset中的2个条件

时间:2012-11-08 17:37:29

标签: tsql group-by multiple-columns

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

enter image description here

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

enter image description here

可以完成这样的事吗?您可以注意到,我们按不同的列进行分组。这不必使用一个查询,但是,它必须最终在一个表/数据集中。

3 个答案:

答案 0 :(得分:2)

我会独立总结每一套,然后使用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]

答案 1 :(得分:0)

好像你需要这个:

select PeriodEarnedYear,
    sum(PeriodEarned) Earned,
    Sale
from yourtable
group by PeriodEarnedYear, Sale

答案 2 :(得分: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

但这会做出一些假设。