我有一个临时表,通过连接3-4个表来创建。结果如下。
NAME EMP_ID CODE Status Department
----------------------------------------------------------------------
SHARIFAH SURAYA BINTI BAHARUDIN 30100359 A IN ENG
FATIN NADIA BINTI MOHAMMAD 30100360 B IN ENG
NOOR AZIAH BINTI MOHD NOOR 30100361 A Absent ENG
NURUL ATIKA BINTI ALI ASAN 30100363 A Absent PACK
SITI UMI KALSOM BINTI AMRAN 30100364 B Absent PACK
ZAINATUL NABILA BINTI ZAINUDIN 30100365 A Absent PACK
MOHD ZARUL BIN ZAUKAFLI 30100367 A IN COM
AIREEN SYAFIRA BINTI JAMALUDIN 30100369 A IN COM
FARAH WAHIDA BINTI MOHD ISA 30100371 C IN PACK
MUHAMAD FAIZAL BIN AZMAN 30100259 A IN COM
SITI NOOR HAFIZAH BINTI ZAKARANI 30100264 A IN PACK
NUR FATEHAH BINTI MISTAM 30100277 Z IN PACK
我希望它能作为数据透视表出现,如下所示:
感谢您的帮助。
答案 0 :(得分:1)
这是使用条件聚合的一种方法
SELECT department,
Concat(Count(CASE WHEN code = 'a' AND status = 'IN' THEN 1 END), '/', Count(CASE WHEN code = 'a' THEN 1 END)),
Concat(Count(CASE WHEN code = 'b' AND status = 'IN' THEN 1 END), '/', Count(CASE WHEN code = 'b' THEN 1 END)),
Concat(Count(CASE WHEN code = 'c' AND status = 'IN' THEN 1 END), '/', Count(CASE WHEN code = 'c' THEN 1 END)),
Concat(Count(CASE WHEN code = 'z' AND status = 'IN' THEN 1 END), '/', Count(CASE WHEN code = 'z' THEN 1 END))
FROM yourtable
GROUP BY department
如果code列中的值未知,则使用dynamic sql
DECLARE @SQL VARCHAR(MAX)= 'SELECT department,'
SET @SQL += (SELECT DISTINCT Concat('Count(CASE WHEN code = ''', code, ''' AND status = ''IN'' THEN 1 END)', '/', 'Count(CASE WHEN code = ''', code, ''' THEN 1 END),')
FROM YOURTABLE
FOR XML PATH(''))
SET @SQL = LEFT(@SQL, Len(@SQL) - 1)
SET @SQL += 'FROM yourtable
GROUP BY department '
--SELECT @SQL
EXEC(@SQL)