Parameter values - sql

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]))
);

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!

New to SQL. Would like to convert an IF(COUNTIFS()) Excel formula to SQL code and have SQL calculate it instead of Excel

I am running SQL Server 2008 R2 (RTM).
I have a SQL query that pulls Dates, Products, Customers and Units:
select
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset
where [Transaction Date] < '2019-03-01' and [Transaction Date] >= '2016-01-01'
group by [Transaction Date], [SKU], [Customer Name]
order by [Transaction Date]
This pulls hundreds of thousands of records and I wanted to determine if a certain transaction was a new order or reorder based on the following logic:
Reorder: That specific Customer has ordered that specific product in the last 6 months
New Order: That specific Customer hasn’t ordered that specific product in the last 6 months
For that I have this formula in Excel that seems to be working:
=IF(COUNTIFS(A$1:A1,">="&DATE(YEAR(A2),MONTH(A2)-6,DAY(A2)),C$1:C1,C2,B$1:B1,B2),"Reorder","New Order")
The formula works when I paste it individually or in a smaller dataset, but when I try to copy paste it to all 500K+ rows, Excel gives up because it loops for each calculation.
This could probably be done in SQL, but I don’t have the knowledge on how to convert this excel formula to SQL, I just started studying it.
You're doing pretty well with the start of your query there. There are three additional functions you're looking to add to your query.
The first thing you'll need is the easiest. GETDATE() simply returns the current date. You'll need that when you're comparing the current date to the transaction date.
The second function is DATEDIFF, which will give you a unit of time between two dates (months, days, years, quarters, etc). Using DATEDIFF, you can say "is this date within the last 6 months". The format for this is pretty easy. It's DATEDIFF(interval, date1, date2).
The thrid function you're looking for is CASE, which allows you to tell SQL to give you one answer if one condition is met, but a different answer if a different condition is met. For your example, you can say "if the difference in days is < 60, return 'Reorder', if not give me 'New Order'".
Putting it all together:
SELECT CASE
WHEN DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 6
THEN 'Reorder'
ELSE 'New Order'
END as ORDER_TYPE
,[Transaction Date] AS DATE
,[SKU] AS PRODUCT
,[Customer Name] AS CUSTOMER
,Qty AS UNITS
FROM DATASET
For additonal examples on CASE, take a look at this site: https://www.w3schools.com/sql/sql_ref_case.asp
For additional examples on DATEDIFF, take a look here: See the
following webpage for examples and a chance to try it out:
https://www.w3schools.com/sql/func_sqlserver_datediff.asp
SELECT CASE
WHEN Datediff(day, [transaction date], Getdate()) <= 180 THEN 'reorder'
ELSE 'Neworder'
END,
[transaction date] AS Date,
[sku] AS Product,
[customer name] AS Customer,
qty AS Units
FROM datase
If I understand correctly, you want to peak at the previous date and make a comparison. This suggests lag():
select (case when lag([Transaction Date]) over (partition by SKU, [Customer Name] order by [Transaction Date]) >
dateadd(month, -6, [Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset d
group by [Transaction Date], [SKU], [Customer Name];
EDIT:
In SQL Server 2008, you can emulate the LAG() using OUTER APPLY:
select (case when dprev.[Transaction Date] >
dateadd(month, -6, d.[Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
d.[Transaction Date] as Date,
d.[SKU] as Product,
d.[Customer Name] as Customer,
sum(d.Qty) as Units
from dataset d outer apply
(select top (1) dprev.*
from dataset dprev
where dprev.SKU = d.SKU and
dprev.[Customer Name] = d.[Customer Name] and
dprev.[Transaction Date] < d.[Transaction Date]
order by dprev.[Transaction Date] desc
) dprev
group by d.[Transaction Date], d.[SKU], d.[Customer Name];

Limiting results in SSRS SQL query

I am trying to build a report on our ticketing system using SSRS. I am bringing in fields from both an "incident body" table and an "incident details" table. What I am looking for is whether the ticket has slipped past an SLA for response to the customer.
I am checking for tickets past SLA two ways:
1) the ticket is past the SLA date and there is no detail record matching the predetermined types
2) the ticket has a detail record matching the predetermined types but it was after the SLA date
I was able to build the CTE section below but I am struggling with how to reduce the result of that to just the oldest matching row/record. A ticket should only show up once in the report.
For example:
Johnny Blogs updates a ticket using the CONTACTED_TM recordtype on 1/1/2016. The SLA was 12/31/2015. The next day (1/2/2016) he also emails the TM using the EMAILOUT recordtype. The CTE returns both these rows/records. I only want the first result.
My query code is below. I have tried using a SELECT TOP 1 in the CTE, but it just causes it to return no results.
WITH CTE (Date, [Action ID], Description, Note, [Login ID], [Seq.Group], [Incident #], ResponseDue) AS
(
SELECT Date, [Action ID], [Incident Details].Description, [Incident Details].Note, [Login ID], [Incident Details].[Seq.Group], [Incident Details].[Incident #], [Incident].[Due Date & Time:] as ResponseDue
FROM [_SMDBA_].[Incident Details]
JOIN [_SMDBA_].[Incident]
ON [Incident Details].[Incident #] = [Incident].[Incident #]
WHERE ([Action ID] = 'CONTACTED_TM' OR [Action ID] = 'TM_UNAVAILABLE' OR ([Action ID] = N'EMAILOUT' AND _SMDBA_.[Incident].[Client Email] in ([Email To Email From])))
--AND Date >= Incident.[Due Date & Time:]
)
SELECT
I.[Incident #]
,I.[Group Name]
,I.[Seq.Group] as IncidentGroupSeq
,I.[Due Date & Time:] as ResponseDue
,I.[Priority ID:]
,I.[Priority Duration]
,I.[Subject ID]
,I.[Open Date & Time] as OpenDate
,I.[Impact ID:] as Impact
,I.[Urgency ID:] as Urgency
,CTE.[Action ID]
,CTE.Description
,CTE.Note
,CTE.[Login ID]
,CTE.Date AS IncidentDetailsDate
,CTE.[Seq.Group] as DetailsGroupSeq
,_SMDBA_.CalcWorkingSeconds(1001,[Due Date & Time:],CTE.Date) as WorkingSecs
,CASE
WHEN CTE.date >= I.[Due Date & Time:] THEN 'Response was Late'
WHEN CTE.Date IS NULL THEN 'There was no response'
WHEN CTE.date <= I.[Due Date & Time:] THEN 'Met SLA'
WHEN I.[Due Date & Time:] IS NULL THEN 'No Response date set'
END AS SLAStatus
FROM [_SMDBA_].Incident I
LEFT OUTER JOIN CTE
ON CTE.[Incident #] = I.[Incident #]
WHERE
I.[Open Date & Time] >= #StartDate
AND I.[Open Date & Time] <= #EndDate
AND I.[Group Name] in (#Group)
AND I.[Impact ID:] in (#Impact)
AND I.[Urgency ID:] in (#Urgency)
AND I.[Opened Group:] = 'SERVICE DESK'
Something like this, as referenced in the comments.
WITH CTE ([Date], [Action ID], Description, Note, [Login ID], [Seq.Group], [Incident #], ResponseDue) AS
(
SELECT
[Date],
[Action ID],
[Incident Details].Description,
[Incident Details].Note,
[Login ID],
[Incident Details].[Seq.Group],
[Incident Details].[Incident #],
[Incident].[Due Date & Time:] as ResponseDue,
row_number() over (partition by [Incident Details].[Incident #] order by [Date] desc) as RN
FROM [_SMDBA_].[Incident Details]
JOIN
[_SMDBA_].[Incident]
ON [Incident Details].[Incident #] = [Incident].[Incident #]
WHERE
([Action ID] = 'CONTACTED_TM' OR [Action ID] = 'TM_UNAVAILABLE' OR
([Action ID] = N'EMAILOUT' AND _SMDBA_.[Incident].[Client Email] in ([Email To Email From])))
--AND Date >= Incident.[Due Date & Time:]
)
SELECT
I.[Incident #]
,I.[Group Name]
,I.[Seq.Group] as IncidentGroupSeq
,I.[Due Date & Time:] as ResponseDue
,I.[Priority ID:]
,I.[Priority Duration]
,I.[Subject ID]
,I.[Open Date & Time] as OpenDate
,I.[Impact ID:] as Impact
,I.[Urgency ID:] as Urgency
,CTE.[Action ID]
,CTE.Description
,CTE.Note
,CTE.[Login ID]
,CTE.Date AS IncidentDetailsDate
,CTE.[Seq.Group] as DetailsGroupSeq
,_SMDBA_.CalcWorkingSeconds(1001,[Due Date & Time:],CTE.Date) as WorkingSecs
,CASE
WHEN CTE.date >= I.[Due Date & Time:] THEN 'Response was Late'
WHEN CTE.Date IS NULL THEN 'There was no response'
WHEN CTE.date <= I.[Due Date & Time:] THEN 'Met SLA'
WHEN I.[Due Date & Time:] IS NULL THEN 'No Response date set'
END AS SLAStatus
FROM [_SMDBA_].Incident I
LEFT OUTER JOIN CTE
ON CTE.[Incident #] = I.[Incident #]
WHERE
I.[Open Date & Time] >= #StartDate
AND I.[Open Date & Time] <= #EndDate
AND I.[Group Name] in (#Group)
AND I.[Impact ID:] in (#Impact)
AND I.[Urgency ID:] in (#Urgency)
AND I.[Opened Group:] = 'SERVICE DESK'
AND CTE.RN = 1

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'

MS Query with multiple Parameters

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.