日期 金额 类型
2011-8-1 20 销售
2011-8-1 5 退货
2011-8-2 30 销售
2011-8-2 10 销售
2011-8-2 10 退货
我想得到这样的结果,按日期合计:
日期 销售金额 退货金额
2011-8-1 20 5
2011-8-2 40 10
请问应该怎么写呢?
8 个解决方案
#1
使用Group By 日期
#2
仅仅用个Group By就把销售和退货的都合并了
#3
SELECT SUM(CASE WHEN 类型='销售' THEN 金额 ELSE 0 END) AS 销售金额
,SUM(CASE WHEN 类型='退货' THEN 金额 ELSE 0 END) AS 退货金额
FROM TB
GROUP BY 日期
#4
SELECT 日期
,SUM(CASE WHEN 类型='销售' THEN 金额 ELSE 0 END) AS 销售金额
,SUM(CASE WHEN 类型='退货' THEN 金额 ELSE 0 END) AS 退货金额
FROM TB
GROUP BY 日期
#5
太牛了,竟然还能用case,我试试去
#6
;with cte as(
select 日期,类型,sum(金额)je from t1 group by 日期,类型
)select a.日期,a.je 销售金额,b.je 退货金额
from cte a full join cte b on a.日期=b.日期 and a.类型='销售' and b.类型='退货'
#7
select convert(varchar(10),日期,120) as 日期,
sum(case 类型 when '销售' then 金额 else 0 end) 销售金额,
sum(case 类型 when '退货' then 金额 else 0 end) 退货金额
from t1
group by 日期
#8
select sum(金额),日期,类型 from t1 group by 日期,类型;
#1
使用Group By 日期
#2
仅仅用个Group By就把销售和退货的都合并了
#3
SELECT SUM(CASE WHEN 类型='销售' THEN 金额 ELSE 0 END) AS 销售金额
,SUM(CASE WHEN 类型='退货' THEN 金额 ELSE 0 END) AS 退货金额
FROM TB
GROUP BY 日期
#4
SELECT 日期
,SUM(CASE WHEN 类型='销售' THEN 金额 ELSE 0 END) AS 销售金额
,SUM(CASE WHEN 类型='退货' THEN 金额 ELSE 0 END) AS 退货金额
FROM TB
GROUP BY 日期
#5
太牛了,竟然还能用case,我试试去
#6
;with cte as(
select 日期,类型,sum(金额)je from t1 group by 日期,类型
)select a.日期,a.je 销售金额,b.je 退货金额
from cte a full join cte b on a.日期=b.日期 and a.类型='销售' and b.类型='退货'
#7
select convert(varchar(10),日期,120) as 日期,
sum(case 类型 when '销售' then 金额 else 0 end) 销售金额,
sum(case 类型 when '退货' then 金额 else 0 end) 退货金额
from t1
group by 日期
#8
select sum(金额),日期,类型 from t1 group by 日期,类型;