首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >sql中聚合需求的子查询

sql中聚合需求的子查询
EN

Stack Overflow用户
提问于 2016-09-18 03:31:00
回答 1查看 30关注 0票数 0

我有一张这样的桌子:

代码语言:javascript
运行
复制
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

我尝试接收type='M‘的ID和总价多个项目的列的输出,以及type='T’的另一个具有相同逻辑的列

对我来说,唯一的办法就是使用多cte,但它有点复杂和庞大:

代码语言:javascript
运行
复制
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

有一种感觉,它可以做得更好(例如使用子查询)-asking你如何可以做到。

附注:

SQLlite的东西将会非常受欢迎!

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-18 03:38:27

也许这会有帮助

代码语言:javascript
运行
复制
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

返回

代码语言:javascript
运行
复制
ID  M       T
1   46.00   0.00
2   0.00    68.00
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39550910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档