简体   繁体   English

SQL中聚合需求的子查询

[英]Subqueries for aggregation needs in sql

I have a table like this: 我有一张这样的桌子:

Id    Date     Price  Item  Type
1  2009-09-21    25     1     M
2  2009-08-31    16     2     T
1  2009-09-23    21     1     M
2  2009-09-03    12     3     T

I try to receive the output of ID and column of sum price mult items for type='M' and another column with same logic for type='T' 我尝试接收类型='M'的ID和总价格多项目列的输出以及类型='T'的具有相同逻辑的另一列

Only way how to do it for me is using multi-cte but it is kind of complex and big: 对我来说,做这件事的唯一方法是使用multi-cte,但这有点复杂而且庞大:

with cte as (
select distinct a.id, a.date
sum(price*a.item) as numm
from table a
where a.type='M'
group by a.id), 

crx as (
select cte.id, cte.numm, sum(a.price*a.item) as numm_1  from cte
join table a on a.id=cte.id and a.date=cte.date
where a.type='T'
group by cte.id)

select * from crx

Having a certain feeling that it can be done better (for example using subqueries)-asking you how can it be done. 有一定的感觉可以做得更好(例如使用子查询)-向您询问如何完成。

ps ps

SQLlite stuff would be greatly appreciated! SQLlite的东西将不胜感激!

Thanks! 谢谢!

Perhaps this will help 也许这会有所帮助

Declare @YourTable table (Id int,Date date,Price money,Item int,Type varchar(25))
Insert into @YourTable values
(1,'2009-09-21',25,1,'M'),
(2,'2009-08-31',16,2,'T'),
(1,'2009-09-23',21,1,'M'),
(2,'2009-09-03',12,3,'T')

Select ID
      ,sum(case when Type='M' then Price*Item else 0 end) as M
      ,sum(case when Type='T' then Price*Item else 0 end) as T
 From  YourTable
 Group By ID

Returns 退货

ID  M       T
1   46.00   0.00
2   0.00    68.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM