Click here to Skip to main content
14,732,921 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
sql server -2008


Need to transpose the fields 'ACCEPT','BEYOND','EXACT' from columns to rows.

How do I code the select statement below to achieve that


DECLARE @sql nvarchar(4000)

SET @sql = 'SELECT A.BRN_NAME ,A.PROD_SERV , A.COMP_TYPE,
COUNT(*) AS OVER_CNT ,
SUM(CASE WHEN DATEADD(DD,P.PROD_SERV_TAT, A.COMP_DATE) < COALESCE(A.DAT_COMP_INV_CLOSE0,A.DAT_COMP_INV_CLOSE,A.DATE_COMP_CLOS_FRMT)
THEN 1 ELSE 0 END) AS ACCEPT,
SUM(CASE WHEN DATEADD(DD,P.PROD_SERV_TAT, A.COMP_DATE) > COALESCE(A.DAT_COMP_INV_CLOSE0,A.DAT_COMP_INV_CLOSE,A.DATE_COMP_CLOS_FRMT)
THEN 1 ELSE 0 END) AS BEYOND,
SUM(CASE WHEN DATEADD(DD,P.PROD_SERV_TAT, A.COMP_DATE) = COALESCE(A.DAT_COMP_INV_CLOSE0,A.DAT_COMP_INV_CLOSE,A.DATE_COMP_CLOS_FRMT)
THEN 1 ELSE 0 END) AS EXACT
FROM RESPONSE A
LEFT JOIN BRANCH C ON A.BRN_NAME = C.BRN_NAME
LEFT JOIN PROD_SERV P ON A.PROD_SERV = P.PROD_SERV_NAME
LEFT JOIN PAYMAST B ON A.LNAME = B.LNAME
AND A.FNAME = B.FNAME
AND A.EMPNO = B.EMPNO
WHERE (A.COMP_DATE BETWEEN @CFROM AND @CTO)'


FROM


BRN_NAME PROD_SERV COMP_TYPE OVER_CNT ACCEPT BEYOND EXACT
-----------------------------------------------------------------------------------------------------------------------------------
Ashanti Region MARINE ABUSIVE 1 1 0 0
Ashanti Region MARINE CLAIMS 2 2 0 0
Ashanti Region MEDICAL CLAIMS 1 0 0 1
Ashanti Region MOTOR ABUSIVE 2 2 0 0
Ashanti Region MOTOR CLAIMS 135 111 24 0
Ashanti Region MOTOR DENIAL 2 2 0 0
Greater Accra MEDICAL CLAIMS 5 0 0 5
Greater Accra MOTOR CLAIMS 127 102 25 0
Northern Region MOTOR CLAIMS 114 91 20 3
Volta Region MOTOR CLAIMS 32 28 4 0


EXPECTED RESULT

BRN_NAME PROD_SERV COMP_TYPE OPINION COUNTS OVER_CNT
----------------------------------------------------------------------------
Ashanti Region MARINE ABUSIVE ACCEPT 1 1
Ashanti Region MARINE ABUSIVE BEYOND 0 1
Ashanti Region MARINE ABUSIVE EXACT 0 1

Etc Etc

------------------------------
------------------------------


Please assist

Thanks

What I have tried:

Ongoing development and stack no example exists after an intensive search on the net
Posted
Updated 2-May-18 3:00am

1 solution

From SQL Server 2008 you can use UNPIVOT to do that - see
Using PIVOT and UNPIVOT | Microsoft Docs[^]
SQL Server Unpivot table - Pinal Dave[^]

As you are trying to do this over multiple columns then this article should also help:
Multi UNPIVOT[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900