如何通过SQL查询检索此架构?

时间:2018-09-25 20:41:24

标签: sql sql-server

这是我的表及其数据:

-------------------------------------
rid  mid  qty   price  tname
-------------------------------------
10   A    1000  400    Buy
11   A    2000  420    Buy
12   B    1700  600    Buy
13   A    600   450    Sell

我想要这样的输出:

----------------------------------------------------------------
mid   SUM_Buy  tname  SUM_Sell  tname  SUM_Buy_minus_SUM_Sell
----------------------------------------------------------------
A     3000     Buy    600       Sell    2400
B     1700     Buy    NULL      NULL    NULL

2 个答案:

答案 0 :(得分:0)

感谢您使用耗材更新您的问题。更好的方法是发布ddl和样本数据,以便人们可以抓取并滚动。我是为你做的。

declare @something table
(
    rid int
    , mid char(1)
    , qty int
    , price int
    , tname varchar(10)
)

insert @something values
(10, 'A', 1000, 400, 'Buy')
, (11, 'A', 2000, 420, 'Buy')
, (12, 'B', 1700, 600, 'Buy')
, (13, 'A', 600 , 450, 'Sell')

以这种格式,其他人可以很容易地获得帮助。

您可以使用条件聚合来解决此问题。我使用tname1和tname2是因为在SSMS之外,您不希望多个列具有相同的名称。但是这些可能只是噪音,并不是真正需要的,因为它们对结果没有任何帮助。

select s.mid
    , Sum_Buy = sum(case when tname = 'Buy' then qty end) 
    , tname1 = 'Buy'
    , Sum_Sell = sum(case when tname = 'Sell' then qty end) 
    , tname2 = 'Sell'
    , SUM_Buy_minus_SUM_Sell = sum(case when tname = 'Buy' then qty end) - sum(case when tname = 'Sell' then qty end)
from @something s
group by s.mid
order by s.mid

答案 1 :(得分:0)

您可以尝试this(将{em> grouping by mid列与case..when语句的贡献汇总一起使用):

with t(rid,mid,qty,price,tname) as
(
select 10,'A',1000,400,'Buy' union all
select 11,'A',2000,420,'Buy' union all
select 12,'B',1700,600,'Buy' union all
select 13,'A',600,450,'Sell'    
)
select t.mid, sum(case when tname='Buy' then qty else 0 end) as SUM_Buy,
       min(case when tname='Buy' then tname else null end) as tname,
       sum(case when tname='Sell' then qty else null end) as SUM_Sell,
       max(case when tname='Sell' then tname else null end) as tname,
       (sum(case when tname='Buy' then qty else 0 end) -
         sum(case when tname='Sell' then qty else null end)) as 
       SUM_Buy_minus_SUM_Sell
  from t
 group by t.mid