在MySQL中组合多行时发出问题

时间:2014-03-21 11:09:49

标签: mysql sql

  1. 我想根据以下条件构建查询
  2. 我只想将总和1和2类型的总和结合起来。
  3. 将2行合并为1并避免该行中的空值。
  4. 查询,

    select B.ID as BillId, 
           I.Id as ItemID, 
           t.Type, 
           SUM(I.TotalPrice) as TotalPrice, 
           Case when t.Type = 1 then SUM(T.Amount) end as TaxAmountType1,
           Case when t.Type = 2 then SUM(T.Amount) end as TaxAmountType2 
      from Bill B
           inner join ItemDetails I 
               on I.BillNoID = B.ID
           inner join TaxDetails T 
               on T.ItemDetailId = I.Id
    group by 
           B.ID, 
           I.Id, 
           I.TotalPrice, 
           t.Type;
    

    请参考下面的图片, enter image description here

    enter image description here 预期产出:

    '1','1',NULL,'40 .00','3.00','5.00'

    注意: 1.我不想使用子查询。 2.预期输出“NULL”表示我不想单独显示该列。

4 个答案:

答案 0 :(得分:0)

听起来这样可以解决您的问题。如果没有,请提供更多信息。

SELECT B.ID as BillId, I.Id as ItemId, 
       t.type, SUM(TotalPrice), SUM(TaxAmountType1), 
       SUM(TaxAmountType2) 
FROM Bill B 
GROUP BY BillId, ItemId, t.type

答案 1 :(得分:0)

请勿按您尝试聚合的列进行分组。从GROUP BY中删除I.TotalPrice:

select B.ID as BillId, I.Id as ItemID, t.Type, SUM(I.TotalPrice) as TotalPrice, 
    Case when t.Type = 1 then SUM(T.Amount) end as TaxAmountType1,
    Case when t.Type = 2 then SUM(T.Amount) end as TaxAmountType2 from Bill B
inner join ItemDetails I on I.BillNoID = B.ID
inner join TaxDetails T on T.ItemDetailId = I.Id
group by B.ID, I.Id, t.Type;`

答案 2 :(得分:0)

尝试

select B.ID as BillId, I.Id as ItemID, null as Type, SUM(I.TotalPrice) as TotalPrice, 
Case when t.Type = 1 then SUM(T.Amount) end as TaxAmountType1,
Case when t.Type = 2 then SUM(T.Amount) end as TaxAmountType2
from Bill B
inner join ItemDetails I on I.BillNoID = B.ID
inner join TaxDetails T on T.ItemDetailId = I.Id
group by B.ID, I.Id, I.TotalPrice

您不希望按类型分组,这是问题(您还可以从选择中删除",null作为类型"

答案 3 :(得分:0)

如果按t.type分组,则无法将这些实例放在同一行中。 尝试:

select B.ID as BillId, I.Id as ItemID, t.Type, SUM(I.TotalPrice) as TotalPrice, 
Case when t.Type = 1 then SUM(T.Amount) end as TaxAmountType1,
Case when t.Type = 2 then SUM(T.Amount) end as TaxAmountType2 from Bill B
inner join ItemDetails I on I.BillNoID = B.ID
inner join TaxDetails T on T.ItemDetailId = I.Id
group by B.ID, I.Id, I.TotalPrice;