Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone, Now I try to select the table, below is now my current select table

Source          total   Local     Overseas     Singapore
ALIBABA           1       0           1            0
ALIBABA           1       0           0            1
BBB               1       1           0            0
GOOGLE ADS        1       1           0            0

Now my problem is how to make "ALIBABA" group together and the result i want is as below
Source          total   Local     Overseas     Singapore
ALIBABA           2       0           1            1
BBB               1       1           0            0
GOOGLE ADS        1       1           0            0


What I have tried:

select gt2.Source,count(Region) as total,
CASE
	WHEN Region = 'MALAYSIA' THEN count(Region)
	ELSE 0
END as LOCAL,
CASE
	WHEN Region = 'OVERSEAS' THEN count(Region)
	ELSE 0
END as OVERSEAS,
CASE
	WHEN Region = 'SINGAPORE' THEN count(Region)
	ELSE 0
END as SINGAPORE
from [ERP_GT].[dbo].[GTMAX_RefTable] as gt1
left join [ERP_GT].[dbo].[GTMAX_Customer] as gt2 on gt2.Region = gt1.Name
where Type='reg' and Created between '2020-05-05' and '2020-05-08'
group by gt2.Source, Region
Posted
Updated 21-Jul-20 20:37pm

1 solution

Try this:

SQL
USE [ERP_GT];

SELECT [OVERSEAS], [MALAYSIA], [SINGAPORE], [OVERSEAS] + [MALAYSIA] + [SINGAPORE] AS Total
FROM 
(
    SELECT gt2.Source, Region, Local
    FROM [GTMAX_RefTable] as gt1
        LEFT JOIN [GTMAX_Customer] as gt2 on gt2.Region = gt1.Name
    WHERE Type='reg' and Created BETWEEN '2020-05-05' and '2020-05-08'

) AS DT
PIVOT(COUNT(*) FOR Region IN ([OVERSEAS], [MALAYSIA], [SINGAPORE])) AS PT



For further details. please see: Using PIVOT and UNPIVOT - SQL Server | Microsoft Docs[^]
 
Share this answer
 
Comments
gan chee siang 22-Jul-20 2:40am    
Solve already and thx u so much
Maciej Los 22-Jul-20 3:46am    
You're very welcome.
Garth J Lancaster 22-Jul-20 4:31am    
well done Maciej :-)
Maciej Los 22-Jul-20 6:57am    
Thank you, Garth.
Sandeep Mewara 22-Jul-20 6:52am    
Nice +5

Catching up after long time! :) How are you.

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