表@sales
的内容基本上是每个城市最畅销的汽车品牌。这是说丰田在 Houston 和 Chicago 等中销售最多。
此查询的结果(我知道可能更好)显示了哪些品牌被绑定以及绑定的次数。例如, Chevy 并列两个城市的第一名, Ford 并列在一个城市(迈阿密),依此类推。
如何根据count(*)
将CarSoldMost
添加到变量中?在这种情况下,我会将2
添加到@chevy
,将1添加到@ford
等等吗?
我正在考虑使用case
语句,但它的使用不正确。
declare @toyota int = 0
declare @nissan int = 0
declare @chevy int = 0
declare @ford int = 0
declare @sales table
(
city varchar(10),
CarSoldMost varchar(10)
)
insert into @Sales
select 'Chicago', 'Toyota' union
select 'Orlando', 'Nissan' union
select 'miami', 'Ford' union
select 'miami', 'Chevy' union
select 'houston', 'Toyota' union
select 'houston', 'Chevy'
select *From @sales
;with cte as
(
select city
from @sales
group by city
having count(*) > 1
) --select carsoldmost, count(*) from @sales where city in (select city from cte)
group by carsoldmost
select @chevy =
case
when carsoldmost = 'chevy' then @chevy+count(*)
when carsoldmost = 'Ford' then @ford+count(*)
end
from @sales where city in (select city from cte) group by carsoldmost
select @chevy, @ford
答案 0 :(得分:1)
变量的分配需要使用单独的case
表达式完成:
-- Sample data.
declare @Sales as Table(
City VarChar(10),
CarSoldMost VarChar(10) );
insert into @Sales ( City, CarSoldMost ) values
( 'Chicago', 'Toyota' ),
( 'Orlando', 'Nissan' ),
( 'Miami', 'Ford' ),
( 'Miami', 'Chevy' ),
( 'Houston', 'Toyota' ),
( 'Houston', 'Chevy' );
select * from @Sales;
-- Summary variables.
declare @Chevy int = 0, @Ford int = 0, @Nissan int = 0, @Toyota int = 0;
-- Summary query.
with cte as (
select City
from @Sales
group by City
having Count(*) > 1 )
select
@Chevy += case when CarSoldMost = 'Chevy' then Count(*) else 0 end,
@Ford += case when CarSoldMost = 'Ford' then Count(*) else 0 end,
@Nissan += case when CarSoldMost = 'Nissan' then Count(*) else 0 end,
@Toyota += case when CarSoldMost = 'Toyota' then Count(*) else 0 end
from @Sales
where City in ( select City from cte )
group by CarSoldMost;
-- Display the results.
select @Chevy as 'Chevy', @ford as 'Ford', @Nissan as 'Nissan', @Toyota as 'Toyota';
答案 1 :(得分:0)
使用条件聚合已经发布的其他变体
-- display result/or replace aliasis by variables to assign values.
select
Chevy = Count(case when CarSoldMost = 'Chevy' then 1 end) ,
Ford = Count(case when CarSoldMost = 'Ford' then 1 end),
Nissan = Count(case when CarSoldMost = 'Nissan' then 1 end),
Toyota = Count(case when CarSoldMost = 'Toyota' then 1 end)
from @Sales as a
Where City in (select City
from @Sales
group by City
having count(City)>1)
测试: