我有点迷失在这里。
我有一个表,该表在同一列中包含多个重复值,我想以S / N和Group作为一个唯一值返回,然后将每个包装的价格在单独的列中显示为('1D'AS DAILY,'每周1W”,“每月1M”。
上午使用MS SQL 2012
预先感谢
致谢, 阿德南
答案 0 :(得分:3)
select [S/N], [group],
sum(case when package = '1D' then price else 0 end) as [daily price],
sum(case when package = '1W' then price else 0 end) as [weekly price],
sum(case when package = '1M' then price else 0 end) as [monthly price]
from rates
group by [S/N], [group]
答案 1 :(得分:0)
您还可以使用PIVOT运算符:
if OBJECT_ID('tempdb..#Rates') is not NULL drop table #Rates
create table #Rates(
S_N int not null,
_group varchar(10) not null,
Package char(2) not null,
price int not null
)
insert into #Rates
values (8, 'D' , '1M', 3700)
,(8, 'I-DC','1M', 1750)
,(8, 'TB', '1M', 7000)
,(12, 'A', '1D', 80)
,(12, 'A', '1W', 480)
,(12, 'A', '1M', 1800)
,(12, 'B', '1D', 90)
,(12, 'B', '1W', 540)
,(12, 'B', '1M', 2100)
select S_N, _group, pvt.[1D] as "DailyPrice1D", pvt.[1W] as "WeeklyPrice1W", pvt.[1M] as "MonthlyPrice1M"
from #Rates
pivot(avg(price) FOR Package in ("1D", "1W", "1M")) pvt
ORDER by S_N
您是否需要更多说明,或者此代码示例足够? 有关更多信息,请参见Microsoft文档:https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017