Suppose you had this table:
CREATE TABLE Records
(
RecordId int IDENTITY(1,1) NOT NULL,
CreateDate datetime NOT NULL,
IsSpecial bit NOT NULL
CONSTRAINT PK_Records PRIMARY KEY(RecordId)
)
Now a report needs to be created where the total records and the total special records are broken down by month. I can use these two queries separately:
-- TOTAL RECORDS PER MONTH
SELECT January, February, March, April, May, June,
July, August, September, October, November, December
FROM (
SELECT RecordId, DATENAME(MONTH, CreateDate) AS RecordMonth
FROM dbo.Records
) AS SourceTable
PIVOT (
COUNT(RecordId) FOR RecordMonth IN (January, February, March, April, May, June,
July, August, September, October, November, December)
) AS PivotTable;
-- TOTAL SPECIAL RECORDS PER MONTH
SELECT January, February, March, April, May, June,
July, August, September, October, November, December
FROM (
SELECT RecordId, DATENAME(MONTH, CreateDate) AS RecordMonth
FROM dbo.Records
WHERE IsSpecial = 1
) AS SourceTable
PIVOT (
COUNT(RecordId) FOR RecordMonth IN (January, February, March, April, May, June,
July, August, September, October, November, December)
) AS PivotTable;
The results might look like this:
Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
total 0 0 2 2 1 0 0 1 2 1 2 4
total special 0 0 1 0 1 0 0 0 0 0 0 2
Is it possible to combine these two queries into a single more efficient query?