透视SQL Server表

时间:2019-07-06 04:15:30

标签: sql sql-server tsql pivot

SQL Server表中的示例数据如下所示:

+------------+---------+---------+-----+-------+--------+--------+
|    Date    | Account |  Head   | D_C | TxnID | AmCode | Amount |
+------------+---------+---------+-----+-------+--------+--------+
| 15-05-2019 |     123 | Savings | D   |     5 | SV     |    150 |
| 15-05-2019 |     123 | Cash    | C   |     5 | SV     |    150 |
| 16-05-2019 |     367 | Loan    | D   |     6 | LN     |    200 |
| 16-05-2019 |     367 | Cash    | C   |     6 | LN     |    200 |
+------------+---------+---------+-----+-------+--------+--------+

上面显示了两对(4行)。除了HeadD_C Column以外,每对中的所有字段都相同(即使数据未排序-尽管它在上面也已排序)。

我正在从上述示例中查找以下报告:

+------------+---------+---------+--------+-------+--------+--------+
|    Date    | Account | D Head  | C Head | TxnID | AmCode | Amount |
+------------+---------+---------+--------+-------+--------+--------+
| 15-05-2019 |     123 | Savings | Cash   |     5 | SV     |    150 |
| 16-05-2019 |     367 | Loan    | Cash   |     6 | LN     |    200 |
+------------+---------+---------+--------+-------+--------+--------+

这是该报表的一行,其中Head + D组合在一行中,而Head + C组合在另一列中。

请注意,在实际数据中,这些对可能不会如上所述一起出现。但是,除Head + D_C之外的其他字段的串联使串联的字符串对于一对行而言是唯一的。

预先感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

尝试条件聚合:

declare @tmp table
(
     [Date]  date,  
     Account int,   
     Head    varchar(50),  
     D_C     char(1),  
     TxnID   int,  
     AmCode  char(2),  
     Amount  int
)

insert into @tmp
values
 ('2019-05-15', 123, 'Savings', 'D', 5, 'SV', 150) 
,('2019-05-15', 123, 'Cash'   , 'C', 5, 'SV', 150) 
,('2019-05-16', 367, 'Loan'   , 'D', 6, 'LN', 200) 
,('2019-05-16', 367, 'Cash'   , 'C', 6, 'LN', 200) 

select  
  [Date]
, Account
, max(case when D_C='D' then Head end )as [D Head]
, max(case when D_C='C' then Head end )as [C Head]
, TxnID
, AmCode
, Amount 
From @tmp
group by [Date], Account, TxnID, AmCode, Amount

结果:

enter image description here

答案 1 :(得分:2)

如果我正确理解这一点,则希望合并具有相同的借方和贷方对:

  • Date
  • Account
  • TxnID
  • AmCode
  • Amount

尽管仍保留有关借方和贷方的Head说明。

;with Debit --Define Debit CTEas only debit lines
as
(
    SELECT *
    FROM datatable
    WHERE D_C='D'
),
Credit  --Define Credit CTE as only debit lines
as
(
    SELECT *
    FROM datatable
    WHERE D_C='C'
)
SELECT DISTINCT --Get only unique lines
    d.[Date],
    d.[Account],
    d.Head as [D Head],
    c.Head as [C Head],
    d.TxnID,
    d.AmCode,
    d.Amount
From [Debit] d
INNER JOIN --Join on all the same fields
    [Credit] c
ON 
    d.Date = c.Date
AND 
    d.Account = c.Account
AND 
    d.TxnID = c.TxnID
AND 
    d.AMCode = c.AmCode
AND 
    c.Amount = d.Amount

上面的代码基于以下事实:每对您只能有一个借方和一个贷方行。如果不是这种情况,则需要修改代码。

输出:

Output