This is for SQL Server 2012: a subset of the data in my CTE looks like this:
Employee | OrderID | OrderType
---------+---------+----------
Kala | 321111 | 953
Paul | 321222 | 1026
Don | 321333 | 1026
Don | 321333 | 953
Kala | 321444 | 953
I'd like the following result:
Employee | 953_Order_Count | 1026_Order_Count
---------+-----------------+-----------------
Kala | 2 | 0
Don | 1 | 1
Paul | 0 | 1
To validate that I want is possible in my mind, when I run:
SELECT
Employee,
OrderType,
COUNT(DISTINCT OrderID) AS 'Count'
FROM
CTE
GROUP BY
employee, ordertype
The following result is returned:
Employee | OrderType | Count
---------+-----------+------
Kala | 953 | 1
Paul | 1026 | 1
Don | 1026 | 1
Don | 953 | 1
Close, but not close enough. So I run:
SELECT
Employee,
COUNT(DISTINCT OrderID) AS 'Total_Orders',
COUNT(DISTINCT (CASE WHEN OrderType = 1026 THEN OrderID END)) AS '1026_Order_Count',
COUNT(DISTINCT(CASE WHEN OrderType = 953 THEN OrderID END)) AS '953_Order_Count'
FROM
CTE
GROUP BY
Employee
The result is an accurate first "count," but the rest return 0. If this were not a CTE, I'd use a recursive statement.
Any help is appreciated!