1

我有一个叫做日志的表。日记有 4 列:

  1. 日期(日期)
  2. 帐户(整数)
  3. Type(varchar(1) (可以接受字符 D 或 C)
  4. 金额(十进制(18,2))

杂志

Date         Account    Amount    Type
2012-05-31   20001      300       D
2012-05-31   20002      700       C
2012-05-31   20003      600       D
2012-05-31   20004      900       C

类型列只能采用 2 种类型的字符值:D 或 C。所以我需要一个查询,它会给我 4 列,这样结果列是:

Date        Account       D       C
2012-05-31  200101        300     0
2012-05-31  200102        0       700
2012-05-31  200103        600     0
2012-05-31  200104        0       900

D 和 C 列填充了来自 Amount 的值,无论它们是否为空。

4

3 回答 3

3

您可以使用PIVOT完成此操作:

create table journal
(
    date datetime,
    account int,
    amount money,
    type varchar(1)
)

insert into journal values ('05/31/12', 20001, 300, 'D')
insert into journal values ('05/31/12', 20002, 700, 'C')
insert into journal values ('05/31/12', 20003, 600, 'D')
insert into journal values ('05/31/12', 20004, 900, 'C')

select date
    , account
    , isnull([D], 0) as D
    , isnull([C], 0) as C
from 
(
    select *
    from journal
) x
pivot
(
    sum(amount)
    for type in ([D], [C])
) p

drop table journal

查看带有演示的SQL Fiddle

如果您想加入帐户名称,那么您将需要在该表上执行 JOIN。请参阅使用演示更新SQL Fiddle :

select date
    , account
    , name
    , isnull([D], 0) as D
    , isnull([C], 0) as C
from 
(
    select *
    from journal j
    inner join account a
      on j.account = a.id
) x
pivot
(
    sum(amount)
    for type in ([D], [C])
) p
于 2012-05-31T15:47:51.087 回答
1
SELECT DATE,
       account,
       CASE
         WHEN TYPE = 'D' THEN
          amount
         ELSE
          0
       END D,
       CASE
         WHEN TYPE = 'C' THEN
          amount
         ELSE
          0
       END C TYPE
  FROM JOURNAL
于 2012-05-31T15:58:28.750 回答
0

你想做这样的事情吗?

SELECT
    SUM(CASE [Type] WHEN 'C' THEN [Amount] ELSE 0 END) AS C
    ,SUM(CASE [Type] WHEN 'D' THEN [Amount] ELSE 0 END) AS D
    ,[Date]
    ,[Account]
FROM
    Journal
GROUP BY
    [Date]
    ,[Account]

这将汇总日期/帐户组合的每个值的金额。您可以用SUM您选择的任何聚合替换聚合(MINMAX

于 2012-05-31T15:47:26.777 回答