Issue with a WHERE clause - sql-server

I any writing a query in SQL Server to display all jobs which were received in the previous week, the query will be the basis of an automated report in Crystal Report, syntax is as below
SELECT TOP (100) PERCENT
DATENAME(yy, dbo.JOB.JOB_TAKEN_DATE) + '-' + DATENAME(wk, DATEADD(wk, - 1, dbo.JOB.JOB_TAKEN_DATE)) AS PERIOD,
dbo.JOB.CUST_ORD_NO AS [ORDER NO],
dbo.JOB.JOB_TAKEN_DATE AS RECEIVED,
dbo.JOB.JOB_COMPLETION_DATE AS COMPLETED,
UPPER(ISNULL(dbo.JOB.PROPERTY_LOCATION, ' ') + ' ' + dbo.JOB.PROPERTY_NAME + ' ' + REPLACE(REPLACE(REPLACE(dbo.JOB.PROPERTY_ADDRESS, CHAR(10), ' '), CHAR(13), ' '), CHAR(9), ' ') + ' ' + dbo.JOB.PROPERTY_POSTCODE) AS ADDRESS,
REPLACE(REPLACE(REPLACE(dbo.JOB.WORKS_TO_BE_CARRIED_OUT, CHAR(10), ' '), CHAR(13), ' '), CHAR(9), ' ') AS [WORKS ORDERED],
dbo.JOB.JOB_TARGET_DATE,
dbo.['TMO properties$'].F2
FROM
dbo.JOB
INNER JOIN
dbo.CUSTOMERPROPERTY ON dbo.JOB.CUSTOMER_PROPERTY_ID = dbo.CUSTOMERPROPERTY.CUSTOMER_PROPERTY_ID
INNER JOIN
dbo.['TMO properties$'] ON dbo.CUSTOMERPROPERTY.EXTERNAL_REFERENCE = dbo.['TMO properties$'].F1
WHERE
DATENAME(yy, dbo.JOB.JOB_TAKEN_DATE) + '-' + DATENAME(wk, DATEADD(wk, - 1, dbo.JOB.JOB_TAKEN_DATE)) = DATENAME(yy, CURRENT_TIMESTAMP) + '-' + DATENAME(wk, DATEADD(wk, - 1, CURRENT_TIMESTAMP))
ORDER BY
RECEIVED
When running the query I get an error
adding a value to a 'date' column caused an overflow
Can anyone see what I am doing wrong?

The only place your error could be coming from in the code provided is:dateadd(week, -1, j.job_taken_date) which appears in both your select and your where.
You can get around this by using datepart() to get the week integer and reducing that by 1 instead of adjusting the date value with: convert(varchar(2),datepart(week,j.job_taken_date)-1).
It looks like your where clause means "jobs taken this week". If that is the case, you can simplify your where to compare dates truncated to the week instead of the string comparison you are building now, which may be causing your error.
You can also make your query easier to read by using table aliases, and not using shorthand with date/time operations.
select top (100) percent
datename(year, j.job_taken_date)
+ '-'
--+ datename(week, dateadd(week, -1, j.job_taken_date)
+ convert(varchar(2),datepart(week,j.job_taken_date)-1)
) as period
, j.cust_ord_no as [order no]
, j.job_taken_date as received
, j.job_completion_date as completed
, upper(isnull(j.property_location, ' ')
+ ' ' + j.property_name + ' '
+ replace(replace(replace(j.property_address, char(10), ' '), char(13), ' '), char(9), ' ')
+ ' ' + j.property_postcode
) as address
, replace(replace(replace(j.works_to_be_carried_out, char(10), ' '), char(13), ' '), char(9), ' '
) as [works ordered]
, j.job_target_date
, tmop.F2
from dbo.job j
inner join dbo.customerproperty cp
on j.customer_property_id = cp.customer_property_id
inner join dbo.['tmo properties$'] tmop
on cp.external_reference = tmop.F1
where dateadd(week, datediff(week, 0, j.job_taken_date), 0)
= dateadd(week, datediff(week, 0, current_timestamp), 0)
order by received

Related

Why am I getting duplicated query records in Oracle 12c database?

I'm doing data extraction and I'm new with Oracle databases, I was given a query by some sort of expert in these matters, but after reviewing the data I exported in a CSV I noticed that there was duplicated data, specifically one record, the query is this one:
SELECT
1 AS SourceID,
to_char(SYSDATE, 'yyyy-mm-dd hh24:mi:ss') as CreatedDateTime
,'PAN' AS Customer_Code
,REPLACE(REPLACE(REPLACE(Trim(tibom010.t$mitm), CHR(13), ' '), CHR(10), ' ') , CHR(9), ' ') AS TopLevelPartNumber
,REPLACE(REPLACE(REPLACE(Trim(itm.t$dsca), CHR(13), ' '), CHR(10), ' ') , CHR(9), ' ') AS TopLevelPartNumberDescription
,tibom010.t$pono AS BOMPositionNumber
,tibom010.t$seqn AS BOMSequence
,REPLACE(REPLACE(REPLACE(Trim(tibom010.t$sitm), CHR(13), ' '), CHR(10), ' ') , CHR(9), ' ') AS ComponentPartNumber
,REPLACE(REPLACE(REPLACE(Trim(itm2.t$dsca), CHR(13), ' '), CHR(10), ' ') , CHR(9), ' ') AS ComponentPartDescription
,tibom010.t$qana AS QuanityPer
,REPLACE(REPLACE(REPLACE(Trim(itm2.t$cuni), CHR(13), ' '), CHR(10), ' ') , CHR(9), ' ') AS UnitOfMeasure
,to_char(New_Time(tibom010.t$indt,'GMT','PDT'), 'yyyy-mm-dd hh24:mi:ss') AS EffectiveDate
,CASE WHEN (tibom010.t$exdt > to_date('01/01/1970','mm/dd/yyyy')) THEN to_char(New_Time(tibom010.t$exdt,'GMT','PDT'), 'yyyy-mm-dd hh24:mi:ss') ELSE NULL END AS ExpirationDate
,REPLACE(REPLACE(REPLACE(Trim(rf.t$lcid), CHR(13), ' '), CHR(10), ' ') , CHR(9), ' ') AS ReferenceDesignatorLocation
,REPLACE(REPLACE(REPLACE(Trim(rf.t$qana), CHR(13), ' '), CHR(10), ' ') , CHR(9), ' ') AS ReferenceDesignatorLocationQuantity
FROM baan.ttibom010335 tibom010
LEFT OUTER JOIN baan.ttcibd001335 itm ON (itm.t$item = tibom010.t$mitm)
LEFT OUTER JOIN baan.ttcibd001335 itm2 ON (itm2.t$item = tibom010.t$sitm)
LEFT OUTER JOIN baan.ttibom020335 rf ON (rf.t$mitm = tibom010.t$mitm AND rf.t$pono = tibom010.t$pono AND rf.t$seqn = tibom010.t$seqn)
start WITH trim(tibom010.t$mitm) LIKE 'PNW%'
connect BY prior tibom010.t$sitm = tibom010.t$mitm;
I found the duplicated data when running this query:
SELECT * FROM baan.ttibom010335 tibom010 where trim(tibom010.t$mitm) = 'PNW-710-000162' and trim(tibom010.t$sitm) = 'PNW-510-000060' AND tibom010.t$seqn = 2;
The query from above returns only one item, however the extraction found 5.
Does it have something to do with the start function or any of the other native functions from the Oracle Database? if so, which one?

I am running a script in SQL Server and get the 'Error converting data type varchar to numeric.'

I am trying to run the script below
SELECT
(ISNULL(AMOUNT, '') + '-' + ISNULL(TRAN_ID, '') + '-' + ISNULL(CONVERT(VARCHAR(8), TRAN_DATE, 112), '-')) AS TRAN_ID_NEW,
ID,
ACCOUNT_STATUS,
ACCT_BAL, ACCT_BAL_DATE,
AMOUNT,
AUTH_IP_ADDRESS,
BRANCH_ID,
ENTRY_TIME,
TRAN_CURRENCY,
TRAN_DATE,
TRAN_ID,
TRAN_PARTICULAR,
TRAN_SUB_TYPE, TRAN_TYPE,
VALUE_DATE,
ACCOUNT,
REF_DESC,
ISNULL(REF_DESC, '') + ' ' + ISNULL(TRAN_PARTICULAR, '') + ' ' + ISNULL(AMOUNT, '') AS TRAN_PARTICULAR_NEW
FROM
Txn;
but I get an error:
'Error converting data type varchar to numeric'
Please any solution

Query is not grouping

Im filling a table and I need this table get the daily sells, but summing and counting, sells and clients by day respectively.
But is not grouping the sales by day this is the QUERY:
insert into VentaDiariaTienda(
Fecha,
VentaDia,
Tda_Codigo,
NumeroClientes,
PromedioVtaCliente,
EditName,
EditDateTime)
select
DATENAME(dw, T_Fecha) + ', ' +
cast(datepart(dd, T_Fecha) as char(2)) + ' ' +
datename(mm, T_Fecha) + ' ' +
cast(datepart(yyyy,T_Fecha) as char(4)),
sum(T_ImporteTotal/1.16),
[FolTda_Codigo],
count(T_Cliente),
sum(T_ImporteTotal/1.16)/count(T_Cliente),
'Admin',
GETDATE()
from #Tickets
group by T_Fecha,[FolTda_Codigo]
and this is the out of this query
Thanks for your replys.
You will have to "round down" the T_Fecha values to a day, so you might try to insert the following records:
SELECT
DATENAME(dw, dt) + ', ' +
DATENAME(dd, dt) + ' ' +
DATENAME(mm, dt) + ' ' +
DATENAME(yy, dt),
SUM(T_ImporteTotal)/1.16,
FolTda_Codigo,
COUNT(T_Cliente),
SUM(T_ImporteTotal)/1.16/COUNT(T_Cliente),
'Admin',
GETDATE()
FROM #Tickets
CROSS APPLY (
VALUES (DATEADD(day, DATEDIFF(day, 0, T_Fecha), 0))
) d (dt)
GROUP BY dt, FolTda_Codigo
My proposition:
You can use format function (since SQL Server 2012, else use Wolfgang Method)
Be carefull with divide by "Count" function. If you result is 0 (by example if T_Client is always null) you will have an error
Not necessary to use "outer apply" instruction in this case, group on by date and not by date and time
Something like this:
SELECT
FORMAT(T_Fecha, 'dddd, dd MMMM yyyy', 'en-US' ),
SUM(T_ImporteTotal)/1.16,
FolTda_Codigo,
COUNT(T_Cliente),
case when COUNT(T_Cliente)=0 then null else SUM(T_ImporteTotal)/1.16/COUNT(T_Cliente) end,
'Admin',
GETDATE()
FROM #Tickets
GROUP BY cast(T_Fecha as date), FolTda_Codigo
For SQL Server 2008, replace format by
DATENAME(dw, T_Fecha) + ', ' + DATENAME(dd, T_Fecha) + ' ' +
DATENAME(mm, T_Fecha) + ' ' + DATENAME(yy, T_Fecha),

How to CONCAT two table columns into one column in SQL Server

I am new to SQL Server. I have a script. Please check the script first
SELECT
WOtask.PK,
WOPK,
TaskNo,
TaskAction = CASE
WHEN WOTask.AssetPK IS NOT NULL
THEN '<b>' + Asset.AssetName + ' [' + Asset.AssetID + ']</b> ' +
CASE
WHEN Asset.Vicinity IS NOT NULL
AND Asset.Vicinity <> ''''
THEN RTRIM(Asset.Vicinity) + ': '
ELSE ''''
END + WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' ('+ 'Range:'+ '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + ' - ' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + ')'
ELSE ''
END
ELSE WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' ('+ 'Range:'+ '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + ' - ' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + ')'
ELSE ''
END
END ,
Rate,
Measurement,
Initials,
Fail,
Complete,
Header,
LineStyle,
WOtask.Comments,
WOtask.NotApplicable,
WOTask.Photo1,
WOTask.Photo2
FROM
WOtask WITH (NOLOCK)
LEFT OUTER JOIN
Asset WITH (NOLOCK) ON Asset.AssetPK = WOTask.AssetPK
LEFT OUTER JOIN
AssetSpecification ON AssetSpecification.PK = WOTask.AssetSpecificationPK
WHERE
(WOPK IN (SELECT WOPK
FROM WO WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK) ON Asset.AssetPK = WO.AssetPK
LEFT OUTER JOIN AssetHierarchy WITH (NOLOCK) ON AssetHierarchy.AssetPK = WO.AssetPK
WHERE WO.WOPK = 10939)
)
ORDER BY
WOPK, TaskNo
and here is the output :
now my requirement is to concat TaskAction and Comment column into single column . i would like to give one example of my requirement : the column must show TaskAction value plus Comment: hi(comment column value) . i have been trying to put CONVERT Function for concat two columns but i couldn't get the result as i have been applying convert function to wrong place .
Please help me with some solution. Thanks in advance
Here is the SQL you should use:
SELECT WOtask.PK
, WOPK
, TaskNo
, TaskAction = CASE
WHEN WOtask.AssetPK IS NOT NULL THEN
'<b>' + Asset.AssetName + ' [' + Asset.AssetID + ']</b> ' + CASE
WHEN Asset.Vicinity IS NOT NULL
AND Asset.Vicinity <> '''' THEN
RTRIM(Asset.Vicinity) + ': '
ELSE
''''
END + WOtask.TaskAction
+ CASE
WHEN CONVERT(VARCHAR, ValueLow) IS NOT NULL
AND CONVERT(VARCHAR, ValueHi) IS NOT NULL
AND Spec = 1 THEN
' (' + 'Range:' + '' + CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueLow, 0))) + ' - '
+ CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueHi, 0))) + ')'
ELSE
''
END
ELSE
WOtask.TaskAction
+ CASE
WHEN CONVERT(VARCHAR, ValueLow) IS NOT NULL
AND CONVERT(VARCHAR, ValueHi) IS NOT NULL
AND Spec = 1 THEN
' (' + 'Range:' + '' + CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueLow, 0))) + ' - '
+ CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueHi, 0))) + ')'
ELSE
''
END
END
, Rate
, Measurement
, Initials
, Fail
, Complete
, Header
, LineStyle
, WOtask.Comments
, WOtask.NotApplicable
, WOtask.Photo1
, WOtask.Photo2
, ISNULL(
CASE
WHEN WOtask.AssetPK IS NOT NULL THEN
'<b>' + Asset.AssetName + ' [' + Asset.AssetID + ']</b> ' + CASE
WHEN Asset.Vicinity IS NOT NULL
AND Asset.Vicinity <> '''' THEN
RTRIM(Asset.Vicinity) + ': '
ELSE
''''
END + WOtask.TaskAction
+ CASE
WHEN CONVERT(VARCHAR, ValueLow) IS NOT NULL
AND CONVERT(VARCHAR, ValueHi) IS NOT NULL
AND Spec = 1 THEN
' (' + 'Range:' + '' + CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueLow, 0))) + ' - ' + CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueHi, 0)))
+ ')'
ELSE
''
END
ELSE
WOtask.TaskAction
+ CASE
WHEN CONVERT(VARCHAR, ValueLow) IS NOT NULL
AND CONVERT(VARCHAR, ValueHi) IS NOT NULL
AND Spec = 1 THEN
' (' + 'Range:' + '' + CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueLow, 0))) + ' - ' + CONVERT(VARCHAR, CONVERT(FLOAT, ISNULL(ValueHi, 0)))
+ ')'
ELSE
''
END
END
, ''
) + ISNULL(WOtask.Comments, '') AS [Single Column]
FROM WOtask WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK) ON Asset.AssetPK = WOtask.AssetPK
LEFT OUTER JOIN AssetSpecification ON AssetSpecification.PK = WOtask.AssetSpecificationPK
WHERE (WOPK IN
(
SELECT WOPK
FROM WO WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK) ON Asset.AssetPK = WO.AssetPK
LEFT OUTER JOIN AssetHierarchy WITH (NOLOCK) ON AssetHierarchy.AssetPK = WO.AssetPK
WHERE WO.WOPK = 10939
)
)
ORDER BY WOPK
, TaskNo;

Correct Amount of Spaces with concatenated person's name in SQL Server

Here is my SQL as I have it now. The first and last name should never be missing because they are required on the interface with validation. However, if the middle initial is missing, I don't want two spaces in the result; I just want one space. I could put a case statement in, but that seems like overkill if SQL already has a function for this purpose. Does anyone know if there is a function for this purpose? What would the code look like?
SELECT ISNULL(contact.firstname, '')
+ ' '
+ ISNULL(contact.middleinitial, '')
+ ' '
+ ISNULL(contact.lastname, '')
FROM dbo.contact
SELECT
ISNULL(contact.firstname, '') +
ISNULL(' ' + contact.middleinitial + ' ', ' ') +
ISNULL(contact.lastname, '')
However, you either should remove ISNULL for firstname, lastname (defined NOT NULL?) or add some trims
SELECT
LTRIM(RTRIM(
ISNULL(contact.firstname, '') +
ISNULL(' ' + contact.middleinitial + ' ', ' ') +
ISNULL(contact.lastname, '')
))
In SQL Server 2012 and up you can use CONCAT function:
SELECT CONCAT(contact.firstname, ' ' + contact.middleinitial, ' ' + contact.lastname)
FROM dbo.contact
If middleinitial is null then appending space to null value will result in null value and CONCAT will skip this null value during concatenation.
SELECT REPLACE(ISNULL(contact.firstname, '') + ' ' + ISNULL(contact.middleinitial, '') + ' ' + ISNULL(contact.lastname, '')
,' ',' ')
FROM dbo.contact

Resources