我正在使用union,以便我可以 "合并 "來自3個獨立查詢的資料。 我的表有很多列,但我必須只使用標題和ID。
我的資料:
ID Title
1 'trainings'
2 '培訓'
3 'workshops'4 'workshopes'5 'Workshop'
6 'qwerty'/span>
7 'qwerty2'
8 'qwerty3'/span>
我想做的是只顯示培訓、研討會的標題,并將其他三個標題合并為 "其他",然后逐一計數。 例如:
計算標題
2 培訓次數
3 研討會
3 其他
我所嘗試的:
select 標題。count(*) as Count From 事件 where Title like '%Training%'
group by Title
union
select 標題。count(*) as count From 事件 where Title like '%Workshop%'
group by Title
union
select 'Others' as 標題。 count(*) as Count from Events e wheree. Title not like '%workshop%' ande. 標題 不 像 '%training%'
Group by Title
但是我沒有得到想要的結果,的確,我按照 "其他 "列取了1:
。Count Title
1 其他
2 培訓課程
3 講習班
但是如果我只運行這段代碼:
select 'Others' as Title, count(*) as Count from Events e wheree. Title not like '%workshop%' ande. 標題 不 像 '%training%'
Group by Title
它可以正常作業,"錯誤 "只是在我與其他兩個人結合時才出現。
你能幫助我解決這個問題嗎?
uj5u.com熱心網友回復:
為什么不直接使用帶有聚合功能的單一查詢呢?
SELECT COUNT(*) AS [ Count] 。
CASE WHEN Title LIKE '%Training%' THEN 'Trainings'
WHEN 標題 LIKE '%Workshop%' THEN 'workshops'
ELSE 'Other'
END AS 標題
FROM dbo.Events
GROUP BY CASE WHEN 標題LIKE '%Training%' THEN 'Trainings'
WHEN 標題 LIKE '%Workshop%' THEN 'workshops'
ELSE 'Other'
END。
如果你不喜歡重復CASE運算式,你可以使用CTE:
WITH Titles AS(
SELECT CASE WHEN 標題LIKE '%Training%' THEN 'Trainings'
WHEN 標題 LIKE '%Workshop%' THEN 'workshops'
ELSE 'Other'
END AS 標題
FROM dbo.Events)
SELECT COUNT(*) AS [ Count],
標題
FROM Titles
GROUP BY Title。
uj5u.com熱心網友回復:
你可以使用一個case運算式進行聚合:
select(case when title in ('Trainings', '車間') then title
else 'Others"
end) 作為標題。
count(*)
from events e
group by (case when title in ('Trainings', '車間') then title
else 'Others"
end)。)
如果你不想重復case運算式,你可以用apply的橫向連接:
select v.title, count(*)
from events e cross join
(values (case when title in ('Trainings' />, '車間')
then title else 'Others'end)
) v(title)
group by v.title。
編輯:
如果你需要LIKE,你只需擴展這個(問題中沒有例子需要這樣做):
select v.title, count(*)。
from events e cross join
(values (case when title like '%trainings%' then 'Training'
when title like '%workshops%'/span> then 'workshop'
else 'Others'
end)
) v(title)
group by v.title。
uj5u.com熱心網友回復:
SELECT COUNT(ID) AS Count, Title FROM (SELECT ID, CASE WHEN Title IN ('training', 'workshop') THEN Title ELSE 'others' END Title FROM 活動) 作為T GROUP BY Title
uj5u.com熱心網友回復:
另一種方法
select * from (
select count(case when Title like '%trainings%' then 1 end) 作為培訓。
count(case when Title like '%workshops%' then 1 end) as workshops,
count(case when Title 不是 像 '%workshops%' 和標題 不 像 '%trainings%' then 1 end) as Other from Events
)選項卡
串列
(
計數 for 標題 in (培訓、研討會、其他)
)
AS UnpivotTable order by Counts
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332046.html
標籤:
