Conversion failed when converting the varchar value 'Email' to data type int - sql

I have a stored procedure that is getting data from some other database tables and and putting them into another table. I am running into an error
Conversion failed when converting the varchar value 'Email' to data type int.
However, I don't see where/how a data conversion would take place.
I have checked the data types for both where I am getting the email address and where I am inserting the email address. They are both set to varchar(255).
DECLARE #prefix varchar(50), #middle varchar(50), #suffix varchar(50),
#companyID int, #companyNm varchar(100),
#badge varchar(50), #title varchar(100), #salutation varchar(50),
#pplType int, #email varchar(255), #specialty int,
#mailpref int, #source int,
#add1 varchar(100), #add2 varchar(100), #city varchar(50),
#state varchar(50), #zip varchar(50), #countryID int,
#phone varchar(50), #ext varchar(50), #fax varchar(50),
#addID int, #addType int, #arrival datetime, #departure datetime,
#regType varchar(50), #mtRegID int
SELECT #regType = regType
FROM Registration
WHERE personID = #personID AND meetingCode = #meetingCode
SELECT
#prefix = [Name Prefix], #middle = Middle, #suffix = [Name Suffix],
#companyID = [Company ID], #companyNm = [Company Name],
#badge = [Badge Name], #title = Title,
#salutation = Salutation, #pplType = [People Type],
#email = Email, #specialty = [Specialty ID], #mailpref = MailPref,
#source = [Source ID]
FROM
MeetingtrakTest.dbo.tblPeople
WHERE
[Person ID] = #personID
SELECT
#add1 = Address1, #add2 = Address2, #city = City, #state = State,
#zip = Zip, #countryID = [Country Id],
#phone = Phone, #ext = Extension, #fax = Fax, #addID = [Address ID]
FROM
MeetingtrakTest.dbo.tblPeopleAddresses
WHERE
[Person ID] = #personID AND [Primary] = 1
SELECT
#arrival = [Meeting Start Date], #departure = [Meeting End Date]
FROM
MeetingtrakTest.dbo.tblMeetings
WHERE
[Meeting Code] = #meetingCode
INSERT INTO tblRegistration ([Person Id], [Pre or On-Site], [Attendee List], [Use Company Name], [Reg Date], [Use Housing Costs], [Use Itinerary Costs], Attended, [Date Entered], [Entered By], [Date Updated], [First Name], [Last Name], [Meeting Code], [Registration Code], [Name Prefix], Middle, [Name Suffix], [Company ID], [Company Name], [Badge Name], Title, Salutation, [People Type], [Email], [Specialty ID], MailPref, Source, [Address 1], [Address 2], City, State, Zip, [Country ID], Phone, Extension, Fax, [Address Id] ,[Address Type], [Arrival Date], [Departure Date])
VALUES (#personID, 1, 1, 1, GETDATE(), 0, 0, 0, GETDATE(), 'etrak', GETDATE(), #first, #last, #meetingCode, #regType, #prefix, #middle, #suffix, #companyID, #companyNm, #badge, #title, #salutation, #pplType, #email, #specialty, #mailpref, #source, #add1, #add2, #city, #state, #zip, #countryID, #phone, #ext, #fax, #addID, #addType, #arrival, #departure);
SET #mtRegID = SCOPE_IDENTITY();

Related

Insert does not work with cursor

I have a problem that my Insert statement doesn't work. I created temp tables, then the insert statement is working based on two columns in this temp tables.
The data exists in the temp tables, but the insert is not working with no error appearing. Thanks in advance
DECLARE JPCUSTOMER_CURSOR CURSOR FOR
SELECT
cu.CustomerNo, jp.ID
FROM
CUSTOMERNO# cu, SalesmanNo# sa, JourneyPlan JP
WHERE
cu.OCCURRENCE = sa.OCCURRENCE
AND jp.AssignedTO = sa.SalesmanNo
OPEN JPCUSTOMER_CURSOR
FETCH NEXT FROM JPCUSTOMER_CURSOR INTO #CUST_ID,#JP_ID
WHILE (##FETCH_STATUS = 0)
BEGIN
INSERT INTO [JPCustomer] ([CustomerID ], [JPID], [Frequency], [StartWeek],
[sat], [sun], [mon], [tue], [wed], [thu], [fri],
[VisitOrder], [ModifiedOn], [ModifiedBy],
[CreatedOn], [Createdby],
[RecordSource], [IsPotential])
VALUES (#CUST_ID, #JP_ID, 4, 1,
1, 1, 1, 1, 1, 1, 1,
NULL, NULL, NULL,
NULL, NULL, 0, 0)
END
CLOSE JPCUSTOMER_CURSOR;
DEALLOCATE JPCUSTOMER_CURSOR;
You don't need a cursor for what you are doing. This will be much faster:
INSERT INTO [JPCustomer] ([CustomerID ],
[JPID],
[Frequency],
[StartWeek],
[sat],
[sun],
[mon],
[tue],
[wed],
[thu],
[fri],
[VisitOrder],
[ModifiedOn],
[ModifiedBy],
[CreatedOn],
[Createdby],
[RecordSource],
[IsPotential])
select cu.CustomerNo,
jp.ID,
4,
1,
1,
1,
1,
1,
1,
1,
1,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
0
from CUSTOMERNO# cu
join SalesmanNo# sa on cu.OCCURRENCE = sa.OCCURRENCE
join JourneyPlan JP on jp.AssignedTO = sa.SalesmanNo
You don't need and shouldn't use a cursor for this. Just an INSERT ... SELECT. EG
with q as
(
select cu.CustomerID CUST_ID, jp.ID JPID
from CUSTOMERNO# cu
join SalesmanNo# sa
on cu.OCCURRENCE = sa.OCCURRENCE
join JourneyPlan JP
on jp.AssignedTO = sa.SalesmanNo
)
INSERT INTO [JPCustomer] ([CustomerID],
[JPID],
[Frequency],
[StartWeek],
[sat],
[sun],
[mon],
[tue],
[wed],
[thu],
[fri],
[VisitOrder],
[ModifiedOn],
[ModifiedBy],
[CreatedOn],
[Createdby],
[RecordSource],
[IsPotential])
SELECT CustomerID,
JPID,
4,
1,
1,
1,
1,
1,
1,
1,
1,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
0
from q;

how do i update column (selmanufacturers_id) from the query

SELECT
'S. J. & G. FAZUL ELLAHIE (PVT) LTD.' AS CompanyName,
'E - 46, S.I.T.E., KARACHI - 75700' AS CompanyAddress,
'admin' login_user, 'crm.sjg.local' selhost,
'admin' sellogin, 'sr_salereport' seltoprint,
'SALES REPORT' selreportTitle, '' selflagType,
'SI' selreportType, '' selfrmDate, '' seltoDate,
'' selfromProductId, '' selac_fromProductId_ac,
'' selbrandId, '' selcustomerId, '' selac_customerId_ac,
'' selgodownId, '' selsmId, '' selsalesmanId, '' selcity,
'' selarea, '' selorders_status, 'S' seldst,
'Invoice' selgroup1, '1' selcurrencyid, 'id' seltype,
'D' seldefUnit, '' selmanufacturers_id, 'Report' selyt0,
CAST(docTypeId as varchar(20)) + CAST(documentId as varchar(20)) groupId1,
[dbo].[ITL_DATE_TO_STRING_FOR_SORTING](refDate) groupTitle1,
'' groupId2, '' selgroup2,'' groupTitle2, *
FROM
[dbo].SR_Sale(null, null, 0, 0, 0, 0, N'', N'', 0, N'SI', 0, 0, 1, N'id', N'D') AS TR
WHERE
docType IN ('SI', 'GYM RECEIPT')
This is a general update statement
FROM dbo.SR_Sale
SET selmanufacturers_id ='xxx'
WHERE (TODO: add where-clause here to specify which row needs to be updated)
Assuming selmanufacturers_id does not exist in [dbo].SR_Sale function but contrary to products_id.
IF (OBJECT_ID('tempdb..#tmp_SR_SALE') IS NOT NULL )
BEGIN
DROP TABLE #tmp_SR_SALE
END
SELECT 'S. J. & G. FAZUL ELLAHIE (PVT) LTD.' AS CompanyName ,
'E - 46, S.I.T.E., KARACHI - 75700' AS CompanyAddress ,
'admin' login_user ,
'crm.sjg.local' selhost ,
'admin' sellogin ,
'sr_salereport' seltoprint ,
'SALES REPORT' selreportTitle ,
'' selflagType ,
'SI' selreportType ,
'' selfrmDate ,
'' seltoDate ,
'' selfromProductId ,
'' selac_fromProductId_ac ,
'' selbrandId ,
'' selcustomerId ,
'' selac_customerId_ac ,
'' selgodownId ,
'' selsmId ,
'' selsalesmanId ,
'' selcity ,
'' selarea ,
'' selorders_status ,
'S' seldst ,
'Invoice' selgroup1 ,
'1' selcurrencyid ,
'id' seltype ,
'D' seldefUnit ,
'' selmanufacturers_id ,
'Report' selyt0 ,
CAST(docTypeId AS VARCHAR(20)) + CAST(documentId AS VARCHAR(20)) groupId1 ,
[dbo].[ITL_DATE_TO_STRING_FOR_SORTING](refDate) groupTitle1 ,
'' groupId2 ,
'' selgroup2 ,
'' groupTitle2 ,
*
INTO #tmp_SR_SALE FROM [dbo].SR_Sale(NULL, NULL, 0, 0, 0, 0, N'', N'', 0, N'SI', 0, 0, 1,
N'id', N'D') AS TR
WHERE docType IN ( 'SI', 'GYM RECEIPT' )
UPDATE #tmp_SR_SALE
SET selmanufacturers_id = 'value here'
WHERE products_id = 9031
SELECT * FROM #tmp_SR_SALE

Add Subtotal & Total to Pivot

I have the following query
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable;
The output looks great but I want a subtotal for each 'Acct' and a Grand Total for the whole thing.
Can anyone help with this?
You can use group by grouping sets as below:
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], sum([2016]) as [2016], sum([2017]) as [2017] FROM
(
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable
) a
group by GROUPING SETS ( [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type] )
ORDER BY [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type];
Based on Kannan Kandasamy's reply I got this which worked beautifully:
SELECT (CASE
WHEN GROUPING([Acct])=0 AND
GROUPING([Customer]) = 1 AND
GROUPING([Code]) = 1 AND
GROUPING([Description]) = 1 AND
GROUPING([Sale Person]) = 1 AND
GROUPING([Region]) = 1 AND
GROUPING([Store Type]) = 1
THEN 'Total '+ [Acct]
WHEN GROUPING([Acct])=1 AND
GROUPING([Customer]) = 1 AND
GROUPING([Code]) = 1 AND
GROUPING([Description]) = 1 AND
GROUPING([Sale Person]) = 1 AND
GROUPING([Region]) = 1 AND
GROUPING([Store Type]) = 1
THEN 'Total'
ELSE [Acct]
END) AS Acct , ISNULL([Customer],'') AS 'Customer', ISNULL([Code],'') AS 'Code', ISNULL([Description],'') AS 'Description', SUM(ISNULL([Value],'')) AS 'Value', ISNULL([Sale Person],'') AS 'Sales Person',
ISNULL([Region],'') AS 'Region', ISNULL([Store Type],'') AS 'Store Type', SUM([2016]) AS '2016', SUM([2017]) AS '2017'
FROM
(
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable
) a
group by GROUPING SETS (( [Acct], [Customer], [Code], [Description], [Sale Person],
[Region], [Store Type]),([Acct]),());

Subquery returned more than 1 value. This is not permitted when the subquery follows =,.. or when the subquery is used as an expression

I have this following stored procedure to make a reservation .I have not done the front end to insert the values so I use the execute stored procedure from the sql server menu to insert into the database but it gives me the subquery returned more than 1 value and 1 row affected message
ALTER PROCEDURE [dbo].[Usp_makereservation]
--roombookingdetails
#refno VARCHAR(50),
#propertyid int,
#roomtype VARCHAR(3),
#groupcode VARCHAR(30),
#companycode VARCHAR(10),
#arrivaldate DATETIME,
#arrivalplan VARCHAR(3),
#departuredate DATETIME,
#departureplan VARCHAR(3),
#createdby INT,
--roombookingguestdetails
#subsrno VARCHAR(50),
#roomno VARCHAR(30),
#guesttitle VARCHAR(30),
#lname VARCHAR(50),
#fname VARCHAR(50),
#mname VARCHAR(50),
#address VARCHAR(100),
#city VARCHAR(30),
#state VARCHAR(30),
#country INT,
#zipcode VARCHAR(50),
#telno VARCHAR(15),
#mobile VARCHAR(15),
#fax VARCHAR(50),
#gueststatus INT,
#designation VARCHAR(50),
#occupation VARCHAR(50),
#arrivalfrom VARCHAR(50),
#departureto VARCHAR(50),
#leader BIT,
#spclinstrctn VARCHAR(1000),
#checkinflg BIT,
--roombookingoccupancy
#singlebooked INT,
#singleprovisional INT,
#singleconfirmed INT,
#singlewaitlisted INT,
#doublebooked INT,
#doubleprovisional INT,
#doubleconfirmed INT,
#doublewaitlisted INT,
#triplebooked INT,
#tripleprovisional INT,
#tripleconfirmed INT,
#triplewaitlisted INT,
#quadbooked INT,
#quadprovisional INT,
#quadconfirmed INT,
#quadwaitlisted INT,
#marketsegID INT,
#businesssrcID INT,
#guestcategoryID INT,
#gueststatusID INT,
#totalpax INT,
#adultpax INT,
#childpax INT,
#infantpax INT,
#extraadultpax INT,
#extrachildpax INT,
#complementarypax INT,
#noshow INT,
#checkinrooms INT,
#checkinpax INT
AS
BEGIN
BEGIN try
BEGIN TRAN
INSERT INTO roombookingdetails
(reservationno,
srno,
refno,
propertyid,
roomtype,
groupcode,
companycode,
arrivaldate,
arrivalplan,
depaturedate,
depatureplan,
createdon,
createdby)
VALUES ((SELECT Isnull(Max(reservationno) + 1, 1)
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingdetails),
#refno,
#propertyid,
#roomtype,
#groupcode,
#companycode,
#arrivaldate,
#arrivalplan,
#departuredate,
#departureplan,
Getdate(),
#createdby)
INSERT INTO roombookingguestdetails
(reservationno,
srno,
subsrno,
roomno,
guesttitle,
lastname,
firstname,
midname,
[address],
city,
[state],
country,
zipcode,
telno,
mobile,
fax,
gueststatus,
designation,
occupation,
arrivalfrom,
depatureto,
leader,
specialinstruction,
checkinflag,
createdon,
createdby)
VALUES ((SELECT [reservationno]
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingguestdetails),
#subsrno,
#roomno,
#guesttitle,
#lname,
#fname,
#mname,
#address,
#city,
#state,
#country,
#zipcode,
#telno,
#mobile,
#fax,
#gueststatus,
#designation,
#occupation,
#arrivalfrom,
#departureto,
#leader,
#spclinstrctn,
#checkinflg,
Getdate(),
#createdby)
INSERT INTO roombookingoccupancy
(reservationno,
srno,
singlebooked,
singleprovisional,
singleconfirmed,
singlewaitlisted,
doublebooked,
doubleprovisional,
doubleconfirmed,
doublewaitlisted,
tripplebooked,
trippleprovisional,
trippleconfirmed,
tripplewaitlisted,
quadbooked,
quadprovisional,
quadconfirmed,
quadwaitlisted,
marketsegmentid,
businesssourceid,
guestcategoryid,
gueststatusid,
totalpax,
adultpax,
childpax,
infantpax,
extraadultpax,
extrachildpax,
complementrypax,
noshow,
checkinrooms,
checkinpax,
createdon,
createdby)
VALUES ((SELECT [reservationno]
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingoccupancy),
#singlebooked,
#singleprovisional,
#singleconfirmed,
#singlewaitlisted,
#doublebooked,
#doubleprovisional,
#doubleconfirmed,
#doublewaitlisted,
#triplebooked,
#tripleprovisional,
#tripleconfirmed,
#triplewaitlisted,
#quadbooked,
#quadprovisional,
#quadconfirmed,
#quadwaitlisted,
#marketsegID,
#businesssrcID,
#guestcategoryID,
#gueststatusID,
#totalpax,
#adultpax,
#childpax,
#infantpax,
#extraadultpax,
#extrachildpax,
#complementarypax,
#noshow,
#checkinrooms,
#checkinpax,
Getdate(),
#createdby)
COMMIT TRAN
END try
BEGIN catch
PRINT 'Rollback'
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage;
ROLLBACK
END catch
END
Here is the query generated after selecting execute stored procedure command
DECLARE #return_value int
EXEC #return_value = [dbo].[Usp_makereservation]
#refno = N'12',
#propertyid = 2,
#roomtype = N'R345',
#groupcode = N'G25',
#companycode = N'C422',
#arrivaldate = N'1/2/3',
#arrivalplan = N'fd',
#departuredate = N'5/2/3',
#departureplan = N'gdfgd',
#createdby = 1,
#subsrno = N'g',
#roomno = N'fgd',
#guesttitle = N'fdf',
#lname = N'gdf',
#fname = N'f',
#mname = N'd',
#address = N'dfg',
#city = N'fdg',
#state = N'fd',
#country = 3,
#zipcode = N'rt',
#telno = N'etr',
#mobile = N'et',
#fax = N'r',
#gueststatus = 4,
#designation = N'ertre',
#occupation = N'tert',
#arrivalfrom = N'ret',
#departureto = N'ret',
#leader = 1,
#spclinstrctn = N'er',
#checkinflg = 1,
#singlebooked = 2,
#singleprovisional = 2,
#singleconfirmed = 3,
#singlewaitlisted = 2,
#doublebooked = 23,
#doubleprovisional = 2,
#doubleconfirmed = 3,
#doublewaitlisted = 23,
#triplebooked = 23,
#tripleprovisional = 23,
#tripleconfirmed = 23,
#triplewaitlisted = 23,
#quadbooked = 2,
#quadprovisional = 3,
#quadconfirmed = 24,
#quadwaitlisted = 23,
#marketsegID = 432,
#businesssrcID = 4,
#guestcategoryID = 234,
#gueststatusID = 234,
#totalpax = 234,
#adultpax = 23,
#childpax = 4,
#infantpax = 234,
#extraadultpax = 23,
#extrachildpax = 4234,
#complementarypax = 23,
#noshow = 4,
#checkinrooms = 234,
#checkinpax = 43232
SELECT 'Return Value' = #return_value
GO
There is chanch that your following statement may returns more than single value.
Please check it.
> SELECT [reservationno] FROM roombookingdetails
You have used it in your insert statement.
You have to usewhere clause,Top operator,Min,Max,Avg in your subquery when there is such type of problem or more then 1 record exist.
Replacing this (SELECT [reservationno] FROM roombookingdetails) from first insert
with this
(SELECT Isnull(Max(reservationno) + 1, 1) FROM roombookingguestdetails)
and this (SELECT [reservationno] FROM roombookingdetails) from second insert
with this (SELECT Isnull(Max(reservationno) + 1, 1) FROM (RoomBookingOccupancy)
solved my problem

Grouping ignoring blank fields

I am having a hard time to identify (and fix) the grouping issue I have with the following query. My data has some Country fields blank and the query is ignoring them, only those with non blank values are converted to rows. I tried removing the country grouping but I get the error "You tried to execute a query that does not include the specified expression "Country" as part of an aggregate function". This is the query I have in Access:
TRANSFORM Count([passed courses].[Course Number])
SELECT [domain].[Account ID], [domain].[Account Name], [passed courses].[Learner Email Address], [passed courses].Category, [passed courses].Country, [passed courses].[Earliest Start_Date], [passed courses].[Latest End_Date]
FROM [Domain Master] AS [domain] INNER JOIN (SELECT d3.ID, d3.[Learner Email Address], d3.[Course Number], d3.[Transcript Status], d3.Domain, c2.Category, [passed levels].Country, [passed levels].[Earliest Start_Date], [passed levels].[Latest End_Date]
FROM
(SELECT [completed courses].[Learner Email Address], [completed courses].[Level], [completed courses].Category, [completed courses].[Completed Count], [completed courses].Country, [learner dates].[Earliest Start_Date], [learner dates].[Latest End_Date]
FROM
(SELECT [courses taken].[Learner Email Address], [courses taken].[Level], [courses taken].Category, Count([courses taken].ID) AS [Completed Count], [courses taken].Country
FROM
(SELECT d1.ID, d1.[Learner Email Address], d1.[Course Number], c1.[Level], c1.Category, d1.[Transcript Status], d1.Country
FROM [Data] AS d1
INNER JOIN [Courses] AS c1 ON d1.[Course Number] = c1.[Course Number]
)
AS [courses taken]
WHERE [courses taken].[Transcript Status] = "Completed"
GROUP BY [courses taken].[Learner Email Address], [courses taken].Level, [courses taken].Category, d1.Country
)
AS [completed courses]
INNER JOIN
(SELECT d2.[Learner Email Address], d2.Country, Min(d2.Start_Date) AS [Earliest Start_Date], Max(d2.End_Date) AS [Latest End_Date]
FROM [Data] AS d2
GROUP BY d2.[Learner Email Address], d2.Country
) AS [learner dates]
ON [completed courses].[Learner Email Address] = [learner dates].[Learner Email Address] AND
[completed courses].Country = [learner dates].Country
WHERE
([courses taken].Category = 'Sales') AND (
(([completed courses].Level = 1) AND ([completed courses].[Completed Count] >=5)) OR
(([completed courses].Level = 2) AND ([completed courses].[Completed Count] >=5)) OR
(([completed courses].Level = 3) AND ([completed courses].[Completed Count] >=1))
) OR
([courses taken].Category = 'Purchase') AND (
(([completed courses].Level = 1) AND ([completed courses].[Completed Count] >=5)) OR
(([completed courses].Level = 2) AND ([completed courses].[Completed Count] >=4)) OR
(([completed courses].Level = 3) AND ([completed courses].[Completed Count] >=1))
)
)
AS [passed levels]
INNER JOIN ([Data] AS d3 INNER JOIN Courses AS c2 ON ((d3.[Course Number] = c2.[Course Number])))
ON ([passed levels].Level = c2.Level) AND ([passed levels].[Learner Email Address] = d3.[Learner Email Address]) AND ([passed levels].Category = c2.Category)
) AS [passed courses] ON [domain].[Partner Domain] = [passed courses].Domain
GROUP BY [domain].[Account ID], [domain].[Account Name], [passed courses].[Learner Email Address], [passed courses].Category, [passed courses].Country, [passed courses].[Earliest Start_Date], [passed courses].[Latest End_Date]
PIVOT [passed courses].[Course Number];
Any help is appreciated!
What if you added a case statement into your query where if country = '' then return a unique GUID else return the Country column value and alias the case as Country
GUID function for access
You may need to wrap the whole query as a sub query to group by the Country aliased column though. This isn't tested, just a concept idea as I can't see any other way of grouping a country and ignoring blanks within the same select, or a less you did 2 selects and did a union instead.
Regards
Liam