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));
答案 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 ║ ║ ║
╚═════════════════╩═════════╩══════════╩═══════╝