貌似你試圖PIVOT
數據,你可以使用這樣的事情,如果你知道的status
價值觀轉變:
select name, [Created], [Opened], [Finalized]
from
(
select u.name,
s.status
from users u
left join process p
on u.id = p.cod_user
left join status s
on p.cod_status = s.id
) src
pivot
(
count(status)
for status in ([Created], [Opened], [Finalized])
) piv
如果你有數目不詳的狀態中變成列,那麼你可以使用動態SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(status)
from status
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT name, ' + @cols + ' from
(
select u.name,
s.status
from users u
left join process p
on u.id = p.cod_user
left join status s
on p.cod_status = s.id
) x
pivot
(
count(status)
for status in (' + @cols + ')
) p '
execute(@query)
如果您沒有訪問PIVOT
功能,那麼你可以使用聚合函數和CASE
聲明覆制它:
select u.name,
sum(case when s.status = 'created' then 1 else 0 end) created,
sum(case when s.status = 'opened' then 1 else 0 end) opened,
sum(case when s.status = 'finalized' then 1 else 0 end) finalized
from users u
left join process p
on u.id = p.cod_user
left join status s
on p.cod_status = s.id
group by u.name
你應該[**'Joins' **](http://beginner-sql-tutorial.com/sql-joins.htm) –
其中的那些三步(詢問部,returing表去,填寫數據表)你卡在? –
我被卡住了查詢。我如何構建這個查詢? – mcamara