Meeting 2 conditions in 2 different columns - sql

I'm trying to run a query where I need very specific conditions to be met:
Sales code is All
Item has Original Price flag set
Item has a price with no Original Price flag set that is the same as the Price with Original Price flag set
Price without Original price flag set must be created after the price with Original price flag
Currently I am using the following query to get the information I need;
select [item no_], [variant code],[unit price including vat],
[original price], [Starting Date], [Ending Date] from [Sales Price]
where [Sales Code] = 'all'
and [Ending Date] = '1753-01-01 00:00:00.000'
This is the example result:
1 means Original Price flag is set and 0 means it is not
The result I need from this query would be to only show these two:

I am assuming you are working with SQL Server as your current query syntax suggests.
If, so you can use lag() :
select sp.*
from (select sp.*,
lag([original price]) over (partition by [item no_] order by [Starting Date]) as prev_price
from [Sales Price] sp
where [Sales Code] = 'all'
) sp
where ([original price] = 1 or prev_price = 1);

let me know if you need me to explain; else its pretty straight forward.
select a.*
from (
select [item no_]
, [variant code]
,[unit price including vat]
, [original price]
, [Starting Date]
, [Ending Date]
,Column_Test = case when ( [original price] = 1 and [original price] = 0 ) and ([Starting Date]<[Ending Date]) then 1 else 0 end
from [Sales Price]
where [Sales Code] = 'all'
and [Ending Date] = '1753-01-01 00:00:00.000'
) a
where Column_Test = 1

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!

Script help - count , total and avg

I have the following script, trying to count how many distinct customers are there , how many distinct orders , what is total of all orders under £15 and its's avg, total of orders above £20 and it's avg.
with consignments as
(select
[Sell-to Customer No_],
[Convert-to Document No_],
ic.[Shipping Agent Service Code],
[Pick Completed DateTime] as [Shipped DateTime],
ROUND((ic.[Amount Including VAT] + ic.Postage + ic.[Gift Wrap Price] +
ic.[Handling Fee] + ic.[Personalisation Fee]),2) as [Document Amount]
from dbo.[Temp$Consignment] ic inner join [dbo].
[Temp$Order] oh
on ic.[Owner Header GuID]=oh.[Order Guid]
where ic.[Shipping Agent Service Code]='secstan' and ic.[Pick Completed
DateTime] >= '2016-11-01T00:00:00.000' AND
ic.[Pick Completed DateTime] <= '2016-11-30T23:59:55.000' ),summary as
(select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from consignments )select * from summary
I have working script like below, but as I am new to sql I am bit confused how to convert above script to below.
select amountclass,[Shipping Agent Service Code],
count(distinct [Sell-to Customer No_]) as Total_customers,
count(*) as Total_orders,
sum([Amount]) as total_revenue,
avg([Amount] * 1.0) as AOV
from
(
select [Sell-to Customer No_], oh.[Original Order No_], [Amount],ic.
[Shipping Agent Service Code],
case when [Amount] <= 20 then 'Under_20'
else 'Over_20'
end as amountclass
from [TBW_BI].[dbo].[Temp$Order] oh INNER JOIN [TBW_BI].[dbo].
[Temp$Consignment] IC
ON IC.[Owner Header GuID]=OH.[Order Guid]
where[order date] >= '2016-09-01' AND
[order date] <= '2016-09-30' AND [COUNTRY]='UNITED KINGDOM' and
[document type] like 'ord%' and ic.[Shipping Agent Service
Code]='secstan'
) dt
group by amountclass,[Shipping Agent Service Code]
order by amountclass,[Shipping Agent Service Code]
It looks like you have a query with a 2 Common Table Expressions (CTE) and you want to convert the CTE to a derived table. First, we can eliminate one of the CTEs.
summary as
(select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from consignments )
select * from summary
The CTE for summary is unnecessary. We can convert that code to this:
select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from consignments
Now, instead of using the consignments CTE; we can copy the sql code within it to create a derived table.
select *,CASE WHEN [Document Amount] > 15 THEN 1 ELSE 0 END as 'Over15'
from (
select [Sell-to Customer No_],
[Convert-to Document No_],
ic.[Shipping Agent Service Code],
[Pick Completed DateTime] as [Shipped DateTime],
ROUND((ic.[Amount Including VAT] + ic.Postage + ic.[Gift Wrap Price] +
ic.[Handling Fee] + ic.[Personalisation Fee]),2) as [Document Amount]
from dbo.[Temp$Consignment] ic
inner join [dbo].[Temp$Order] oh on ic.[Owner Header GuID]=oh.[Order Guid]
where ic.[Shipping Agent Service Code]='secstan'
and ic.[Pick Completed
DateTime] >= '2016-11-01T00:00:00.000'
AND
ic.[Pick Completed DateTime] <= '2016-11-30T23:59:55.000' ) as t

DATEDIFF displaying null values

I have used DATEDIFF to distinguish between when the first unit rate was created and the posting date is when the first transaction of that item was posted.
I have the result that I need , however the DateDiff function gives me NULL values starting date for some rows.
SELECT DISTINCT b.[Entry No_] ,
a.[Starting Date],
b.[Posting Date],
b.[Item No_],
b.[Invoiced Quantity],
a.[Litre Conversion Factor],
a.[Unit Rate] ,
b.[Location Code],
a.[Excise Location],
a.[Excise Type Code],
a.[Unit Of Measure Code]
FROM [Spier Live$Value Entry] b
LEFT JOIN [Transfer Excise Tbl] a
ON a.[No_] = b.[Item No_]
AND b.[Location Code] = a.[Location Code]
AND DateDiff(y,b.[Posting Date],a.[Starting Date]) > -365 --DateDiff Year -365 for starting date
AND DateDiff(y,b.[Posting Date],a.[Starting Date]) < 0 --DateDiff Yer < 0 for posting date
WHERE b.[Posting Date] > '2013-02-26' --This is when the unit rate was entered
AND b.[Gen_ Bus_ Posting Group] IN ('LOCA','EXSA')
AND b.[Invoiced Quantity] <>0 --Removing all zero values
AND b.[Item No_] = 'F00335'
ORDER BY b.[Posting Date]
My Result
Transfer Excise Tbl This is the table I am joining on
As alex points out in the comments, you're looking for things with datediffs based on day of year, not year. Did you mean <= 0, btw? These criteria don't make sense and so probably aren't what you really want. If so, they'd cause joins to fail where you don't really want them to, leading to nulls showing for table a columns.

Adding New Records from one table with existing and new records to another table in SQL

I'm trying to to append data to a table that contains all the data up to this point. Every week I will be pulling in the new data (which will contain data already existing in the All table) and adding the new records. I added a few test data to the temp table where the generic, material num, etc. are all different but when I run this query it still says it is adding 0 records. Please help.
INSERT INTO ExtWafersAll ( generic, [material number], description, vendor, [net price], [std price], NumberOfDups )
SELECT
ExtWafersTemp.generic,
ExtWafersTemp.[material number],
ExtWafersTemp.description,
ExtWafersTemp.vendor,
ExtWafersTemp.[net price],
ExtWafersTemp.[std price],
ExtWafersTemp.NumberOfDups
FROM ExtWafersTemp
RIGHT JOIN ExtWafersAll
ON (ExtWafersAll.NumberOfDups = ExtWafersTemp.NumberOfDups)
AND (ExtWafersAll.[std price] = ExtWafersTemp.[std price])
AND (ExtWafersAll.[net price] = ExtWafersTemp.[net price])
AND (ExtWafersAll.vendor = ExtWafersTemp.vendor)
AND (ExtWafersAll.description = ExtWafersTemp.description)
AND (ExtWafersAll.[material number] = ExtWafersTemp.[material number])
AND (ExtWafersAll.generic = ExtWafersTemp.generic)
WHERE
ExtWafersTemp.vendor <> ExtWafersAll.vendor
OR ExtWafersTemp.description <> ExtWafersAll.description
OR ExtWafersTemp.[material number] <> ExtWafersAll.[material number]
OR ExtWafersTemp.generic <> ExtWafersAll.generic;
So for example in ExtWafersTemp we have:
Generic Material Number Description Vendor Net Price Std Price
j2151 sjkdga215 xxx125125 TMA 12 14
asdg asgasg aggsggs asg 15 18
And then in ExtWafersAll:
Generic Material Number Description Vendor Net Price Std Price
j2151 sjkdga215 xxx125125 TMA 12 14
I can't figure out how to add the new record thats in the temp to the all file
Maybe this would suit your need:
insert into ExtWafersAll ( generic, [material number], description, vendor, [net price], [std price], NumberOfDups )
select generic, [material number], description, vendor, [net price], [std price], NumberOfDups
from ExtWafersTemp
except
select generic, [material number], description, vendor, [net price], [std price], NumberOfDups
from ExtWafersAll;
In above snippet you add records from ExtWafersTemp table which are not present in ExtWafersAll table. Is this what are you trying to achieve?
About "except" operator you could read here: http://en.wikipedia.org/wiki/Set_operations_%28SQL%29
UPDATE
As it occurred to be MS Access problem you could try to test this:
SELECT
ExtWafersTemp.generic,
ExtWafersTemp.[material number],
ExtWafersTemp.description,
ExtWafersTemp.vendor,
ExtWafersTemp.[net price],
ExtWafersTemp.[std price],
ExtWafersTemp.NumberOfDups
FROM ExtWafersAll RIGHT JOIN ExtWafersTemp
ON (ExtWafersAll.NumberOfDups = ExtWafersTemp.NumberOfDups
AND ExtWafersAll.[std price] = ExtWafersTemp.[std price]
AND ExtWafersAll.[net price] = ExtWafersTemp.[net price]
AND ExtWafersAll.vendor = ExtWafersTemp.vendor
AND ExtWafersAll.description = ExtWafersTemp.description
AND ExtWafersAll.[material number] = ExtWafersTemp.[material number]
AND ExtWafersAll.generic = ExtWafersTemp.generic)
WHERE ExtWafersAll.NumberOfDups is null
AND ExtWafersAll.[std price] is null
AND ExtWafersAll.[net price] is null
AND ExtWafersAll.vendor is null
AND ExtWafersAll.description is null
AND ExtWafersAll.[material number] is null
AND ExtWafersAll.generic is null
Genarally it is a following pattern (in example there is a primary key field - id):
select tt.id
from tableall t right join tabletemp tt
on (t.id = tt.id)
where t.id is null
Hope that it helps.

SQL Result Set Merge

I have a limitation where I can only send one result set to a reporting application at any one time, to produce an end report for a customer.
So a query like this
select
[AGENT],
[TRANSDATE],
[RECIPT NO],
[CUSTOMER NAME],
[ORDER NO] ,
[TRANS NO] ,
QUANTITY,
[AMOUNT COST],
From [Customer] C
However I need lots of totals at the bottom such as this query for some of the columns. I cannot make any changes to front end due to it being a legacy reporting application.
select
Sum ( QUANTITY ) as [SUM OF QUANTITY] ,
Sum ( AMOUNT COST ) AS [SUM OF AMOUNT COST]
From [Customer] C
Obviously I simplified the queries I am using. So the question is how to make 2 results sets one result set in SQL?
Union and union all failed due to date columns being defaulted if you use blank for a column in end application.
Rollup or Pivoting or CTE I kinda thought of but cannot see a solution yet.
what about windowed functions?
like...
select
[AGENT],
[TRANSDATE],
[RECIPT NO],
[CUSTOMER NAME],
[ORDER NO] ,
[TRANS NO] ,
QUANTITY,
[AMOUNT COST],
Sum ( QUANTITY ) over () as [SUM OF QUANTITY] ,
Sum ( [AMOUNT COST] ) over () AS [SUM OF AMOUNT COST]
From [Customer] C