JOIN 2从一个表中选择查询

时间:2012-05-31 15:42:35

标签: sql sql-server

我有一张名为journal的表。 期刊有4栏:

  1. 日期(日期)
  2. 帐户(int)的
  3. 类型(varchar(1)(可以接受字符D或C)
  4. 量(十进制(18,2))
  5. 作者

    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
    

    type列只能使用两种类型的字符值: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中的值,无论它们是否为空。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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等)