MS Query with multiple Parameters - sql-server-2012

I have this SQL Query and i want the results in an Excel 2013 sheet / table
SELECT
[MS Part Number], [Item Name], SUM([Aantal]) AS Aantal, [Prijs]
FROM
(
SELECT
[MS Part Number], [Item Name], SUM([Aantal]) AS Aantal, [Prijs]
FROM
vwSPLAInformatie
WHERE
(DATEPART(YEAR, fakdat) = '2013')
AND (DATEPART(QUARTER, fakdat) = '1')
AND docnumber LIKE '%kwartaal%'
GROUP BY
[MS Part Number], [Item Name], [Aantal], [Prijs]
UNION ALL
SELECT
[MS Part Number], [Item Name], SUM([Aantal]) AS Aantal, [Prijs]
FROM
vwSPLAInformatie
WHERE
(DATEPART(YEAR, fakdat) = '2013')
AND (DATEPART(MONTH, fakdat) = '1')
AND NOT docnumber LIKE '%kwartaal%'
GROUP BY
[MS Part Number], [Item Name], [Aantal], [Prijs]
) AS Basis
GROUP BY
[MS Part Number], [Item Name], [Prijs]
It works perfectly, the only thing is that i have 4 parameters that i want to connect to 3 cell values in Excel.
(Year = 2013) (Quarter = 1) (Month = 2). But when i adjust my Query to the following:
WHERE (DATEPART(YEAR, fakdat) = '?')
And i select the cell in Excel that says 2013, so basicly it should work, but it doensn't. I get the following error:
[Microsoft]ODBC SQL Server][SQL Server]Conversion failed when converting the varchar value '?' to data type in.
The value is the same, but it does not work at all. How can i fix this? I would be extremely happy when this works! In forward, many thanks.

Related

Failed to convert NVARCHAR to INT, but I'm not trying to

I get this error:
Msg 245, Level 16, State 1, Line 5
Conversion failed when converting the nvarchar value 'L NOVAK ENTERPRISES, INC' to data type int.
I've been wrestling with this query for quite a while and just can't figure out in what place that the conversion is being attempted. Using SQL Server 2017.
DECLARE #StartDate AS DateTime
DECLARE #MfgGroupCode AS Varchar(20)
SET #StartDate='2/27/2020'
SET #MfgGroupCode = 'VOLVO_NLA'
SELECT DISTCINT
CT.No_ AS [Contact Number],
CT.Name AS [Contact Name],
UAL.Time AS [Search Date],
UAL.Param1 AS [Search Part],
CT.[E-Mail] AS [Contact Email],
CT.[Phone No_] AS [Contact Phone],
CT.[Company Name] AS [Search By Customer],
(SELECT C.Name
FROM dbo.[Customer] C
WHERE C.No_ = SL.[Sell-to Customer No_]
AND C.Name <> '') AS [Sold To Customer],
SL.[Posting Date] AS [Invoice Date],
SL.[Document No_] AS [Invoice],
SL.Quantity AS [Quantity],
SL.[Unit Price] AS [Unit Price],
SL.Amount AS [Amount],
DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) AS [Interval]
FROM
dbo.[User Action Log] UAL
JOIN
dbo.[User Action Types] UAT ON UAL.[User Action ID] = UAT.ID
JOIN
dbo.[Item] I ON UAL.Param1 = I.[OEM Part Number]
JOIN
dbo.[Contact] CT ON UAL.[Contact No_] = CT.No_
LEFT OUTER JOIN
dbo.[Sales Invoice Line] SL ON UAL.Param1 = SL.[OEM Part Number]
AND SL.[Posting Date] >= #StartDate
WHERE
UAT.Name IN ('SinglePartSearch', 'MultiPartSearch')
AND UAL.[MFG Group Code] = #MfgGroupCode
AND UAL.Time >= #StartDate
AND UAL.Param3 > 0
-- AND DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) < 0 -- Uncomment to see Current Searches with Past Orders
-- AND DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) > -1 -- Uncomment to see Searches resulting in Future Order
AND DATEDIFF(DAY, UAL.Time, SL.[Posting Date]) IS NULL -- Uncomment to See Searches with no Order
ORDER BY
Interval DESC
Thanks to all of your help and questioning, I was able to identify that the culprit is UAL.Param3.
The User Action Log table stores a variety of different "Actions" and the parameters that are affiliated with each type of action (param1, param2, param3). For one action "RequestForAccess", the "L NOVAK" value is perfectly acceptable. For this query, we're looking at the "SinglePartSearch" and "MultiPartSearch" actions, which will only contain numeric values in UAL.Param3
I replaced this line (AND UAL.Param3 > 0) with (AND ISNUMERIC(UAL.Param3) = 1 AND UAL.Param3 <> 0) in the Where clause and it is now returning the results I hoped for.
Let me know if there is a more correct way of doing this and thank you to all who contributed!

Selecting values only for last day of month

I have a query that's supposed to grab only the value for the last day of the month from all my existing records (so the last day of multiple months). I'm unable to get the value I'm needing for ONLY the last day, due to using a SUM() clause. This is adding all the values for the whole month together. Can I get only the value for the last day another way? Is there something I'm missing?
Code so far:
SELECT
ID,
[Customer Name],
Year([ValDate]) & IIf(Len(Month([ValDate]))>1,Month([ValDate]),"0" & Month([ValDate])) AS BalMonth,
Sum(Value) AS LastValue
FROM
Archive
GROUP BY
ID,
[Customer Name],
Year([ValDate]),
Month([ValDate])
ORDER BY
ID,
Year(ValDate) & Month(ValDate)
Other Code tested:
SELECT
ID,
[Customer Name],
YEAR([ValDate]) & MONTH([ValDate]) & MAX(DAY([BalDate])) AS LastDayofMonth
FROM
Archive
GROUP BY
ID ,
[Customer Name],
YEAR([ValDate]),
MONTH([ValDate])
ORDER BY
ID,
[Customer Name],
YEAR([ValDate]),
MONTH([ValDate])
The second section of code didn't work as it produces the dates in YYYYMMDD format. This makes it so it doesn't allow proper ordering of the dates. Instead, the dates are being ordered as 1 , 10 , 11 , 12 , 2 , 3 , 4 , etc.
If anything is unclear I'll try my best to clarify, just let me know!
Try something like:
SELECT
ID,
[Customer Name],
[ValDate] AS LastDayofMonth,
Sum([FieldToSum]) As Total
FROM
Archive
GROUP BY
ID,
[Customer Name],
[ValDate]
HAVING
[ValDate] = DateSerial(Year([ValDate]), Month([ValDate]) + 1, 0)
Edit:
To have a formatted date output, try this:
SELECT
ID,
[Customer Name],
Format([ValDate], "yyyymmdd") AS LastDayofMonth,
Sum([FieldToSum]) As Total
FROM
Archive
WHERE
[ValDate] = DateSerial(Year([ValDate]), Month([ValDate]) + 1, 0)
GROUP BY
ID,
[Customer Name],
Format([ValDate], "yyyymmdd")

Parameter values

can anyone tell me why the following query is asking me for parameter values. It should be (or at least I want to) populating the table with data 'from' where it's pulling it from:
SELECT [BILLING_REJECTS_orig].[ORG NBR] AS BK,
[BILLING_REJECTS_orig].[ACCOUNT NUMBER] AS ACCT,
[BILLING_REJECTS_orig].APPL AS AP,
[BILLING_REJECTS_orig].[ACCOUNT NAME] AS [ACCT NAME],
[BILLING_REJECTS_orig].[TMO NAME],
IIf(Len(DatePart("m", [BILLING_REJECTS_orig]![REPORT DATE])) = 1, Year([BILLING_REJECTS_orig]![REPORT DATE]) & "-" & "0" & Month([BILLING_REJECTS_orig]![REPORT DATE]), Year([BILLING_REJECTS_orig]![REPORT DATE]) & "-" & Month([BILLING_REJECTS_orig]![REPORT DATE])) AS [ACTIVITY MONTH]
INTO Billing_Rejects_Orig
FROM dbo_BILLING_REJECTS_DEPT,
TM_Report_Date
WHERE (
((Year([Billing_Rejects_Orig]![REPORT DATE])) = Year([TM_Report_Date]![Report_Date]))
AND ((Month([Billing_Rejects_Orig]![REPORT DATE])) = Month([TM_Report_Date]![Report_Date]))
);
As #WEI_DBA points out with incorrect reference to table, consider using table aliases as shown with b and t. This cuts down SQL code and is a helpful tool in maintainability as you can then switch out the table name in FROM or JOIN clauses without a whole re-write of query, assuming same structured table.
Especially in MS Access being a default backend database (Jet/ACE) that can be switched out with other RDBMS's (SQL Server, MySQL, etc.) and occasionally used for prototyping, table aliases can help in migration between both linked and local tables.
SELECT b.[ORG NBR] AS BK,
b.[ACCOUNT NUMBER] AS ACCT,
b.APPL AS AP,
b.[ACCOUNT NAME] AS [ACCT NAME],
b.[TMO NAME],
IIf(Len(DatePart('m', b.[REPORT DATE])) = 1,
Year(b.[REPORT DATE]) & '-' & '0' & Month(b.[REPORT DATE]),
Year(b.[REPORT DATE]) & '-' & Month(b.[REPORT DATE])) AS [ACTIVITY MONTH]
INTO Billing_Rejects_Orig
FROM dbo_BILLING_REJECTS_DEPT b,
TM_Report_Date t
WHERE (
((Year(b.[REPORT DATE])) = Year(t.[Report_Date]))
AND ((Month(b.[REPORT DATE])) = Month(t.[Report_Date]))
);

Querying from multiple linked Excel files

I currently have linked multiple Excel files to Access (one file for each month) and I want to create a query from each file that will give me a "master query." All the files are exactly the same with the headings and format. I cannot merge all three and then link because it is well over the Excel Maximum.
I tried this and it gives me the error Data type mismatch in criteria expression
SELECT [Created Date], [Store Name], ProductID, [Customer First Name] & " " & [Customer Last Name] AS CustomerName
FROM August2015
WHERE ProductID = 1587996 OR ProductID = 1587985
UNION
SELECT [Created Date], [Store Name], ProductID, [Customer First Name] & " " & [Customer Last Name] AS CustomerName
FROM July2015
WHERE ProductID = 1587996 OR ProductID = 1587985
UNION
SELECT [Created Date], [Store Name], ProductID, [Customer First Name] & " " & [Customer Last Name] AS CustomerName
FROM June2015
WHERE ProductID = 1587996 OR ProductID= 1587985
Can someone point me in the right direction. Thanks.
Sounds like ProductID is a string. If so:
WHERE ProductID = '1587996' OR ProductID = '1587985'

Sql Query with inner select [duplicate]

This question already has answers here:
Sql query to create a calculated field
(2 answers)
Closed 8 years ago.
I have this sql query:
SELECT DISTINCT
[Card NO],
[User Name],
(
SELECT
MIN(DateTime) AS [Enter Time],
MAX(DateTime) AS [Exit Time],
MAX(DateTime) - MIN(DateTime) AS [Inside Hours]
FROM
ExcelData
)
FROM
ExcelData
GROUP BY
[Card NO], [User Name], DateTime
Table Schema: CardNO | UserName | DateTime
I tried to execute it but with no success. I says that it is an invalid query.
Can anyone find what is wrong in this query?
This would not resolve your possible Problems with reserved keywords and column names, but should be a valid query. You were using a select query as column Name.
SELECT
[Card NO],
[User Name],
MIN(DateTime) AS [Enter Time],
MAX(DateTime) AS [Exit Time],
MAX(DateTime) - MIN(DateTime) AS [Inside Hours]
FROM
ExcelData
GROUP BY
[Card NO], [User Name]
You are grouping by DateTime, which is a reserved keyword, and you don't select a column DateTime. You do select aggregates over DateTime, which means you shouldn't group on it. #irene got the right answer.