SQL信息显示在一行中

时间:2018-10-12 08:55:14

标签: sql sql-server group-by

@Directive({ selector: 'navigator' })
export class NavigatorDirective {

  @Input('navigator.condition') condition: boolean;

  constructor(private router: Router) {}

  @HostBinding('click', ['$event'])
  doSomething(event: MouseEvent) {
    if (this.condition) this.router.navigate(url); // [routerLink]
    else window.location.href = url; // href
  }
}

我得到以下结果:

我的问题是,当会员同时转让和购买股份时,我希望该信息成行显示,而不是单独显示。 例如。一个ID为63的成员,拥有31股优先股和50股已购买股票。我的查询给了我2行:第一行具有0的已转让股票和50的已购买股票,第二行具有31的已转让股票和0的已购买股票。我想要的是此信息显示在一行中。

很遗憾,我还不能附加任何图像。

注意!我在SQL Server 2012中执行此查询。

有什么想法吗? 提前致谢!

2 个答案:

答案 0 :(得分:1)

正如我在评论中所说,请停止使用隐式联接。不再是1989年: Bad habits to kick : using old-style JOINs

这里不需要2个不同的SELECT语句。使用正确的JOININ返回数据,并在CASE中使用简单的SUM表达式:

SELECT CA.MEMBER_ID,
       SUM(CASE APPL_TYPE WHEN 5 THEN CA.NUMBER_OF_SHARES END) AS TRANSFERRED_SHARES, --APPL_TYPE is missing table alias
       SUM(CASE APPL_TYPE WHEN 2 THEN CA.NUMBER_OF_SHARES END) AS PURCHASED_SHARES, --APPL_TYPE is missing table alias
       '-' AS DELETED_SHARES
FROM COS_APPLICATIONS CA
     JOIN COS_APPL_DETAILS CAD ON CA.APPLICATION_ID = CAD.APPLICATION_ID
WHERE APPL_TYPE IN (2, 5) --APPL_TYPE is missing table alias
  AND CA.SERVICE_PRODUCT = 38002
  AND CAD.TRX_TYPE = 'INITIAL'
  AND CAD.TRX_UNIT = 143
GROUP BY CA.MEMBER_ID
ORDER BY CA.MEMBER_ID;

答案 1 :(得分:0)

在顶层使用聚合

select MEMBER_ID,sum(TRANSFERRED_SHARES) as TRANSFERRED_SHARES ,sum(PURCHASED_SHARES) as URCHASED_SHARES
from 
(SELECT CA.MEMBER_ID,
    0 AS TRANSFERRED_SHARES ,
    SUM(CA.NUMBER_OF_SHARES) AS PURCHASED_SHARES, 
    '-' AS DELETED_SHARES
FROM COS_APPLICATIONS CA , COS_APPL_DETAILS CAD
WHERE APPL_TYPE =2
    AND CA.APPLICATION_ID = CAD.APPLICATION_ID
    AND CA.SERVICE_PRODUCT = 38002
    AND CAD.TRX_TYPE = 'INITIAL'
    AND CAD.TRX_UNIT = 143
    GROUP BY CA.MEMBER_ID
UNION ALL
SELECT CA.MEMBER_ID,
    SUM(CA.NUMBER_OF_SHARES) AS TRANSFERRED_SHARES, 
    0 AS PURCHASED_SHARES ,
    '-' AS DELETED_SHARES
FROM COS_APPLICATIONS CA , COS_APPL_DETAILS CAD
WHERE APPL_TYPE =5
   AND CA.APPLICATION_ID = CAD.APPLICATION_ID
   AND CA.SERVICE_PRODUCT = 38002
   AND CAD.TRX_TYPE = 'INITIAL'
   AND CAD.TRX_UNIT = 143 
   GROUP BY CA.MEMBER_ID
)X GROUP BY MEMBER_ID

或使用条件聚合

SELECT CA.MEMBER_ID,
        SUM(case when APPL_TYPE =5 then CA.NUMBER_OF_SHARES end) AS TRANSFERRED_SHARES ,
        SUM(case when APPL_TYPE =2 then CA.NUMBER_OF_SHARES end) AS PURCHASED_SHARES, 
        '-' AS DELETED_SHARES
    FROM COS_APPLICATIONS CA inner join COS_APPL_DETAILS CAD
    on CA.APPLICATION_ID = CAD.APPLICATION_ID
    where 
        CA.SERVICE_PRODUCT = 38002
        and CAD.TRX_TYPE = 'INITIAL'
        AND CAD.TRX_UNIT = 143
        GROUP BY CA.MEMBER_ID