将sql中的数据聚合到一行

时间:2014-09-11 20:20:52

标签: sql

我有这张桌子

person_id   Pay_seq Pay_cd      Pay1_Amt    Pay2_Amt    Pay3_Amt    Pay4_Amt
1234          1     2341       -38257.68    NULL        NULL        NULL
1234          2     3421        NULL        0.00        NULL        NULL
1234          3     4321        NULL        NULL        0.00        NULL
1234          4     4321        Null        NULL        NULL        NULL

并希望有一个像这样的表

person_id   Pay_cd1  Pay1_Amt    Pay_cd2    Pay2_Amt Pay_cd3    Pay3_Amt Pay_cd4    Pay4_Amt
1234        2341    -$38,257.68  3421       $0.00    4321       $0.00    4321       $0.00

我如何在sql中执行此操作?

1 个答案:

答案 0 :(得分:1)

您的数据未规范化,难以查询数据。无论如何,我相信你是在追求(SQL Fiddle)

SELECT person_id, 
  t1.Pay_cd AS Pay_cd1, t1.Pay1_Amt, 
  t2.Pay_cd AS Pay_cd2, t2.Pay2_Amt,
  t3.Pay_cd AS Pay_cd3, t3.Pay3_Amt,
  t4.Pay_cd AS Pay_cd4, t4.Pay4_Amt
FROM MyTable t1
  LEFT JOIN MyTable t2 ON t1.person_id = t2.person_id and t2.Pay_seq = 2
  LEFT JOIN MyTable t3 ON t1.person_id = t3.person_id and t3.Pay_seq = 3
  LEFT JOIN MyTable t4 ON t1.person_id = t4.person_id and t4.Pay_seq = 4
WHERE t1.Pay_seq = 1

如果您的值为null并希望它返回0.00,那么您可以执行以下操作:

CASE WHEN t4.Pay4_Amt IS NULL THEN 0.00 ELSE t4.Pay4_Amt END AS Pay4_Amt

因此完整查询看起来像(SQL Fiddle):

SELECT t1.person_id, 
  t1.Pay_cd AS Pay_cd1, t1.Pay1_Amt, 
  t2.Pay_cd AS Pay_cd2, CASE WHEN t2.Pay2_Amt IS NULL THEN 0.00 ELSE t2.Pay2_Amt END AS Pay2_Amt,
  t3.Pay_cd AS Pay_cd3, CASE WHEN t3.Pay3_Amt IS NULL THEN 0.00 ELSE t3.Pay3_Amt END AS Pay3_Amt,
  t4.Pay_cd AS Pay_cd4, CASE WHEN t4.Pay4_Amt IS NULL THEN 0.00 ELSE t4.Pay4_Amt END AS Pay4_Amt
FROM MyTable t1
  LEFT JOIN MyTable t2 ON t1.person_id = t2.person_id and t2.Pay_seq = 2
  LEFT JOIN MyTable t3 ON t1.person_id = t3.person_id and t3.Pay_seq = 3
  LEFT JOIN MyTable t4 ON t1.person_id = t4.person_id and t4.Pay_seq = 4
WHERE t1.Pay_seq = 1