【问题标题】:Month wise sum + PIVOT in sql serversql server中的每月总和+ PIVOT
【发布时间】:2020-02-11 23:54:36
【问题描述】:

我在一个表中有 2 列金额和日期

Amount   |  Date (MM/DD/YYYY)

5         01/01/19
10        02/01/19
10        03/01/19
10        03/21/19
10        04/21/19

预期结果:

01/01    02/01   03/01   04/01
  5        10      20      10

【问题讨论】:

标签: sql sql-server database sql-server-2008


【解决方案1】:

试试下面的查询

  select DECODE(to_char(date), 'MM'), '04', sum(amount) ) AS 01/01,
     DECODE(to_char(date), 'MM'), '05', sum(amount) ) AS 02/01,
     DECODE(to_char(date), 'MM'), '06', sum(amount) ) AS 03/01,
     DECODE(to_char(date), 'MM'), '07', sum(amount) ) AS 04/01,
     DECODE(to_char(date), 'MM'), '08', sum(amount) ) AS 05/01,
     DECODE(to_char(date), 'MM'), '09', sum(amount) ) AS 06/01,
     DECODE(to_char(date), 'MM'), '10', sum(amount) ) AS 07/01,
     DECODE(to_char(date), 'MM'), '11', sum(amount) ) AS 08/01,
     DECODE(to_char(date), 'MM'), '12', sum(amount) ) AS 09/01,
     DECODE(to_char(date), 'MM'), '01', sum(amount) ) AS 10/01,
     DECODE(to_char(date), 'MM'), '02', sum(amount) ) AS 11/01,
     DECODE(to_char(date), 'MM'), '03', sum(amount) ) AS 12/01 from t

【讨论】:

    【解决方案2】:

    如果你知道你想要的列,你可以使用条件聚合(或pivot):

    select sum(case when month(date) = 1 then amount end) as [01/01],
           sum(case when month(date) = 2 then amount end) as [02/01],
           sum(case when month(date) = 3 then amount end) as [03/01],
           sum(case when month(date) = 4 then amount end) as [04/01]
    from t
    where date >= '2019-01-01' and date < '2020-01-01'
    

    如果您想要一组动态的列,那么您需要一个动态枢轴。单个select 无法做到这一点。

    【讨论】:

    • 这应该是“20190101”和“20200101”,或“2019-01-01T00:00:00.000”,否则如果服务器/用户/登录语言不是英语,则会出现语法错误。好吧,有趣的是,不是 01-01,而是 01-31。
    • @StefanSteiger 。 . .据我所知,ISO 8601 标准 YYYY-MM-DD 适用于除一个(默认为 YDM 的法语设置)之外的所有国际化设置。因为它是标准的,所以我更喜欢它而不是没有连字符。
    • 如果语言是德语,则解释为 YYYY-DD-MM。由于 DD 可以大于 12,因此在这些情况下会抛出异常。 YYYYMMDD 无处不在。因为碰巧你有 DD = MM,所以没关系 - 但只有在这种情况下 - 它仍然是错误的。示例:SET LANGUAGE 德语; SELECT CAST('2019-01-01' AS datetime) AS d UNION ALL SELECT CAST('2019-12-31' AS datetime) AS d
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    相关资源
    最近更新 更多