如何将两行选择为单行输出

时间:2013-12-20 16:29:15

标签: sql sql-server

select语句现在看起来像这样

The select statement looks like this right now

这里我得到了相同stg_edi835_id的两行输出,我想在一行中为该stg_edi835_id选择结果。

输出应该如下所示

enter image description here

有些人可以帮我这么做吗

提前致谢..

3 个答案:

答案 0 :(得分:1)

您的问题有点不完整(您应该显示所需的输出),但是,这里有一个您可以做的样本:

  • 摆脱您不需要的所有独特价值。 (第1列,包含ID等)
  • 在其余部分使用聚合函数。

示例:

Select
   --column 1 removed
   MAX(column2) as ID,
   MAX(column3) as RefID,
   --column 4 removed
   --column 5 removed
   --column 6 removed
   SUM(column7) as Ad1,
   --column 8 removed
   --column 9 removed
   SUM(column10) as Ad2
From
   table

答案 1 :(得分:1)

SELECT STG_EDI835_PLB_ID, STG_EDI835_ID, ADJUSTMENTREASONCODE1, ADJUSTMENTIDENTIFIER1, SUM(NTVE_ADJUSTMENTAMOUNT1_T1+NTVE_ADJUSTMENTAMOUNT1_T2) AS ADJUSTMENTAMOUNT1,
SUM(PTVE_ADJUSTMENTAMOUNT1_T1+PTVE_ADJUSTMENTAMOUNT1_T2) AS ADJUSTMENTAMOUNT2, ADJUSTMENTREASONCODE2, ADJUSTMENTIDENTIFIER2
FROM
(
    SELECT T1.STG_EDI835_PLB_ID , T2.STG_EDI835_ID, T1.ADJUSTMENTREASONCODE1, T1.ADJUSTMENTIDENTIFIER1, 
    (CASE WHEN T1.ADJUSTMENTAMOUNT1 < 0 THEN T1.ADJUSTMENTAMOUNT1 ELSE 0 END) AS NTVE_ADJUSTMENTAMOUNT1_T1,
    (CASE WHEN T2.ADJUSTMENTAMOUNT1 < 0 THEN T2.ADJUSTMENTAMOUNT1 ELSE 0 END) AS NTVE_ADJUSTMENTAMOUNT1_T2,
    (CASE WHEN T1.ADJUSTMENTAMOUNT1 >= 0 THEN T1.ADJUSTMENTAMOUNT1 ELSE 0 END) AS PTVE_ADJUSTMENTAMOUNT1_T1,
    (CASE WHEN T2.ADJUSTMENTAMOUNT1 >= 0 THEN T2.ADJUSTMENTAMOUNT1 ELSE 0 END) AS PTVE_ADJUSTMENTAMOUNT1_T2,
    COALESCE(T2.ADJUSTMENTREASONCODE1, 'NULL') AS ADJUSTMENTREASONCODE2, COALESCE(T2.ADJUSTMENTIDENTIFIER1, NULL) AS ADJUSTMENTIDENTIFIER2
    FROM TABLE1 AS T1
    INNER JOIN TABLES T2
    ON T2.STG_EDI835_ID = T1.STG_EDI835_ID
    AND T2.STG_EDI835_PLB_ID = T1.STG_EDI835_PLB_ID 
) A 
GROUP BY STG_EDI835_PLB_ID, STG_EDI835_ID, ADJUSTMENTREASONCODE1, ADJUSTMENTIDENTIFIER1, ADJUSTMENTREASONCODE2, ADJUSTMENTIDENTIFIER2

答案 2 :(得分:0)

尝试类似

的内容
WITH DATA As (
select 697 as Stg_EDI835_Id, -87.75 as AdjustmentAmount1 union
select 697, -4.64 union
select 612, -6.39 union
select 612, 60.75
)
select SUM(AdjustmentAmount1) AS AdjustmentAmount1, 0 AS adjustmentamount2 FROM DATA GROUP BY Stg_EDI835_Id HAVING SUM(AdjustmentAmount1) <= 0 UNION
select 0, SUM(AdjustmentAmount1)FROM DATA GROUP BY Stg_EDI835_Id HAVING SUM(AdjustmentAmount1) > 0

输出

AdjustmentAmount1 | Adjustmentamount2
    -92.39        |      0.00
      0.00        |     54.36