行在Pivot列中重复

时间:2016-02-27 12:19:22

标签: sql sql-server tsql pivot

select AccountTitle, [January], [February], [March] 
 [dbo].MyReport 
pivot
(
sum(amount)
    for [ReportMonth] in (January, February, March)
) as P


accounttile      January  February   March
-----------------------------------------------------------
Visa             3320     null       null
Medical          1635     null       null
Commission       4400     null       null
Staff Allowance  1215     null       null   
Medical          null     1636.00    null
Commission       null     2200.00    null
Staff Allowance  null     null       1750.00                     

使用此查询

accounttile              January    February    March
-----------------------------------------------------------
Visa                     3320       null        null
Medical                  1635       1636.00     null
Commission               4400       2200.00     null
Staff Allowance          1215       null        1750.00     

现在你可以看到医疗,佣金,员工津贴都是重复的。 2月份未能正常进行

期望的结果是

#include <type_traits>

template <typename...>
using void_t = void;

template <typename, template <typename> class>
auto detect_impl(char) -> std::false_type;

template <typename T, template <typename> class Operation>
auto detect_impl(int) -> decltype(void_t<Operation<T>>(), std::true_type{});

template <typename T, template <typename> class Operation>
using detect = decltype(detect_impl<T, Operation>(0));

1 个答案:

答案 0 :(得分:1)

您可能在示例中显示了更多列

LiveDemo1

使用子查询仅获取AccountTitle, ReportMonth, amount

SELECT AccountTitle, [January], [February], [March] 
FROM (SELECT AccountTitle, ReportMonth, amount FROM MyReport) AS s
PIVOT ( 
  SUM(amount) for [ReportMonth] in (January, February, March) 
) AS pvt

LiveDemo2

输出:

╔═════════════════╦═════════╦══════════╦═══════╗
║   AccountType   ║ January ║ February ║ March ║
╠═════════════════╬═════════╬══════════╬═══════╣
║ Commission      ║ 4400    ║     2200 ║       ║
║ Medical         ║ 1635.82 ║     1636 ║       ║
║ Staff Allowance ║ 1215    ║          ║  1750 ║
║ Visa            ║ 3320    ║          ║       ║
╚═════════════════╩═════════╩══════════╩═══════╝