【问题标题】:Create column with values based on join使用基于连接的值创建列
【发布时间】:2019-12-10 16:34:35
【问题描述】:

我有两个表1)客户表 2)帐户表。我想查看哪些帐户是主要帐户,哪些是次要帐户。

在一张桌子上我有accountRowId。在另一张表中,我有 PrimaryAccountRowIdSecondaryAccountRowId 和“AccountNumber”。

对于我的输出,我希望将所有 AccountNumbers 放在一个列中,并将所有 AccountRelationship(primary or seconday) 放在每个 AccountNumber 旁边的另一列中。

为了加入表,对于PrimaryAccounts,我将在PrimaryAccountRowId 上加入AccountRowId,对于辅助帐户,我只需翻转而不是primaryAccountRowId,而是SecondaryAccountRowId

我的帐户表:

  AccountRowId = 256073
  AccountRowId = 342300

客户表:

   PrimaryAccountRowId = 256073
   SecondaryAccountRowId = 342300
   AccountNumber = 8003564
  AccountNumber = 2034666

我想看到我的桌子是什么样子的

     AccoundNumber        AccountRelationship
      8003564             Primary
      2034666             Secondary

请提供一些有用的逻辑/代码,说明我将如何实现这些结果。

来自 OP 的 cmets 这里是表结构。

Create table Customer
(
    AccountNumber Varchar(50)
    , PrimaryAccountRowId Varchar(15)
    , SecondaryAccountRowId Varchar(15)
); 

Create table Account
( 
    AccountRowId Varchar(15)
);

【问题讨论】:

  • 我认为您需要提供表结构。您的客户表中没有两列名称 AccountNumber。
  • @SeanLange 我有一个 AccountNumber 列我只是在说我的表中有什么我有两个 accountNumber 值和两个不同的 accountrowid 值
  • 所以分享你的表格结构。这不会很难查询,但如果没有表定义,这只是猜测。
  • 一列怎么有2个值?一列只有 1 个值,而不是 2 个。
  • @Larnu 每个记录一个,请参阅我提供的信息

标签: sql sql-server join unpivot


【解决方案1】:

我在这里仍然有些猜测。您需要提供表结构、示例数据和所需的输出,以便人们轻松帮助您。类似的东西。

declare @Customer table
(
    AccountNumber Varchar(50)
    , PrimaryAccountRowId Varchar(15)
    , SecondaryAccountRowId Varchar(15)
)

insert @Customer values
('8003564', '256073', null)
, ('2034666', null, '342300')

declare @Account table
(
    AccountRowid Varchar(15)
)

INSERT @Account values
('256073'), ('342300')

现在我们有了一些可以使用的表和数据,这只是条件聚合的一个例子。据我了解,这应该会返回您正在寻找的数据。

select c.AccountNumber
    , AccountRelationship = max(case when p.AccountRowId is not null then 'Primary' when c.SecondaryAccountRowId is not null then 'Secondary' end)
from @Customer c
left join @Account p on p.AccountRowid = c.PrimaryAccountRowId
left join @Account s on s.AccountRowid = c.SecondaryAccountRowId
group by c.AccountNumber
order by AccountRelationship

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 2015-01-13
    相关资源
    最近更新 更多