I've recently been tasked with migrating some code stacks for an applicatin that is moving from using Access to using SQL-Server.
I don't usually use Pivot all that much, and most of my code is scripting intended for in-house administration of our SQL Servers. As such my code is not that great.
USE [Database1]
GO
SELECT
Region,
Year,
Month,
SalesPersonNR,
(ISNULL(SUM(SalesA),0) + ISNULL(SUM(SalesB),0) + ISNULL(SUM(SalesC),0) + ISNULL(SUM(Sales),0) + ISNULL(SUM(NA),0)) AS Total,
SUM(Sales) Sales,
SUM(SalesA) SalesA,
SUM(SalesB) SalesB,
SUM(SalesC) SalesC
FROM
(
SELECT
Region,
Year,
Month,
SalesPersonNR,
COUNT(SalesNumber) as total,
expr1
FROM (
SELECT A.Region,
Year([Date]) AS Year,
Month([Date]) AS Month,
A.SalesPersonNR,
A.SalesNumber AS SalesNumber,
CASE
WHEN B.DateSalesC IS NOT NULL THEN 'SalesC'
WHEN B.DateSalesB IS NOT NULL THEN 'SalesB'
WHEN B.DateSalesA IS NOT NULL THEN 'SalesA'
WHEN B.DateSales IS NOT NULL THEN 'Sales'
ELSE 'NA'
END AS expr1
FROM [Table1] A
JOIN [Table2] B
ON A.SalesNumber = B.SalesNumber
WHERE
A.Status = 99
) Internal
GROUP BY
Region,
Year,
Month,
SalesPersonNR,
expr1
) AS x
PIVOT
(
SUM(Total)
FOR expr1 IN (SalesC, SalesB, SalesA, Sales, NA)
) AS y
GROUP BY
Region,
Year,
Month,
SalesPersonNR
How could I clean up this code, and make it easier to maintain.
My main concern is, I want this simpler, but how?