if a number in column is negative,show positive,else show the number - sql-server

I have a [Preko]column in a query that is calculating the difference between two columns.If the number is negative,I need to show it positive,and if it is positive,it should stay the same.I can't use ABS in this one.I tried with the case,but it didn't work.
The problem I am getting is that column Preko is invalid.
This is the code for my second try with iif:
SELECT FP.Firma
,FP.NazFirme
,FP.Konto
,FP.NazivKonta
,FP.Partner
,FP.NazivPartnera
,Sum(FP.Duguje) AS dug
,Sum(FP.Potrazuje) AS pot
,Sum(IIf([FP].[Konto] Like '2*'
,[duguje]-[potrazuje]
,[potrazuje]-[duguje])) AS USaldo
,Sum(IIf([datumval]<= '1.1.2017'
,IIf([FP].[Konto] Like '2*'
,[duguje]-[potrazuje]
,[potrazuje]-[duguje]),0)) AS [Preko]
,IIf([Preko]<0,0,[Preko]) AS Preko1
FROM tblFinansijskiPodaci FP
Where FP.Firma = 1
AND FP.Partner=1110
GROUP BY FP.Firma
,FP.NazFirme
,FP.Konto
,FP.NazivKonta,
,FP.Partner
,FP.NazivPartnera
HAVING (((FP.Konto)=2040))

You can also use a case statement instead of the iif section.
CASE WHEN Preko<0 THEN 0 ELSE Preko END
or
CASE WHEN Preko<0 THEN -Preko ELSE Preko END
That seems to be more in line with your logic depending on how you want to handle the negatives.

Agree with HoneyBadger - ABS is the way to go ABS(-1) returns 1. Have a look at the APEX SQL tools for a quick formatting option. It's free and makes your code a lot easier to read, which means you'll find you get more answers.

WITH cte AS (
SELECT FP.Firma
,FP.NazFirme
,FP.Konto
,FP.NazivKonta
,FP.Partner
,FP.NazivPartnera
,Sum(FP.Duguje) AS dug
,Sum(FP.Potrazuje) AS pot
,Sum(IIf([FP].[Konto] Like '2*'
,[duguje]-[potrazuje]
,[potrazuje]-[duguje])) AS USaldo
,Sum(IIf([datumval]<= '1.1.2017'
,IIf([FP].[Konto] Like '2*'
,[duguje]-[potrazuje]
,[potrazuje]-[duguje]),0)) AS [Preko]
FROM tblFinansijskiPodaci FP
Where FP.Firma = 1
AND FP.Partner=1110
GROUP BY FP.Firma
,FP.NazFirme
,FP.Konto
,FP.NazivKonta,
,FP.Partner
,FP.NazivPartnera
HAVING (((FP.Konto)=2040))
)
SELECT *, CASE WHEN Preko<0 THEN 0 ELSE Preko END preko1 FROM cte

Related

Getting invalid column name in SQL/Excel

I will preface this by saying I am nowhere near being an expert in SQL. Using Excel I am trying to use one specific cell as the input to query, but I run into a problem where a column I created isn't defined as a column. Please help.
SELECT
CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0 THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1) ELSE TCPIPADDRESS END AS IPADDRESS,
ADMachine.ADMachineName, ADMachine.SerialNumber,
ADMachine.OperatingSystem, ADUsers.ADUser, ADUsers.ADDisplayName, employee_data.employee_first_name,
employee_data.employee_last_name, asset_center.LOCATION_SITENAME, asset_center.TCPIPHOSTNAME,
asset_center.MAC_ADDRESS, ADUsers.ADUserOU
FROM PC_GAP.dbo.ADMachine ADMachine, PC_GAP.dbo.ADUsers ADUsers, PC_GAP.dbo.asset_center asset_center, PC_GAP.dbo.employee_data employee_data
WHERE ADUsers.ADUser = employee_data.employee_user_name AND ADMachine.SerialNumber = asset_center.SERIALNO AND ADUsers.ADUser = asset_center.LAST_LOGGED_ON_USER
The IPAddress at the end is where the problem lies.
Edit 1: Added the additional information from the SQL statement to paint the whole picture (originally left out irrelevant data)
Alright so first off you need to stop using the old style joins for all of the reasons listed here.
You are also going to run into an issue that you aren't joining on anything other than one of your tables. I'm pretty sure this will not give you the results that you are looking for.
Then finally you need to think about the order of operations. Since the WHERE clause is evaluated before the the select you cannot refer to your alias in the where clause. You can only reference an alias with an ORDER BY or by using a subquery or a cte.
You can however use your case expression in your where clause. The example would be as follows.
CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0
THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1)
ELSE TCPIPADDRESS
END = ?
As stated previously you could also turn this entire thing into a subquery. I would use your code as an example for that but I'm not entirely sure what exactly you're hoping to accomplish with your current set of joins so my example will be a bit generic.
select
GenericColumn
(select
blah as Pity,
GenericColumn
from dbo.TheFoo)
where Pity = SeachCondition
You can't use a column alias in the WHERE clause. You have to use the whole formula that you aliased.
WHERE ADMachine.SerialNumber = asset_center.SERIALNO AND ((CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0 THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1) ELSE TCPIPADDRESS END=?))
To illustrate Aaron's suggestion, it would look more like this:
WITH cte AS (
SELECT
CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0 THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1) ELSE TCPIPADDRESS END AS IPADDRESS,
ADMachine.ADMachineName,
ADMachine.OperatingSystem,
asset_center.MAC_ADDRESS,
FROM PC_GAP.dbo.ADMachine ADMachine, PC_GAP.dbo.ADUsers ADUsers, PC_GAP.dbo.asset_center asset_center, PC_GAP.dbo.employee_data employee_data
)
SELECT * FROM cte
WHERE ADMachine.SerialNumber = asset_center.SERIALNO AND ((IPAddress=?))

Postgres CASE statement

I cant seem to make the CASE part work
SELECT ROUND((SUM((to_number(g.grade, '9D99') * s.subjunits)))/(SUM(s.subjunits)), 2), CASE WHEN g.grade='DRP' THEN '5.00' END
FROM (grade g
INNER JOIN registration r ON r.grade_id = g.grade_id)
INNER JOIN subject s ON s.subjcode = r.subjcode
WHERE g.grade NOT IN ('INC', 'W', 'INP')
AND r.sy = right(to_char(extract(year from now()- interval '1 year'),'9999'), 4)||'-'||right(to_char(extract(year from now()), '9999'),4)
AND r.sem IN ('1', '2')
AND r.studid='2012-0004'
GROUP BY g.grade;
all I really want is to do is, if a student has a grade of DRP it'll automatically be counted as 5.0 so that the database could include DRP in calculating the GPA.
but it just says
ERROR: invalid input syntax for type numeric: " "
********** Error **********
ERROR: invalid input syntax for type numeric: " "
SQL state: 22P02
currently using postgresql 9.3.2
A case statement returns a value that has nothing inherently to do with any of the values that you fed into it. You seem to be thinking that your case statement will update the value of g.grade. It won't. I think what you want to do is use a case statement in place of the value for g.grade in your first function. Maybe:
SELECT ROUND((SUM((to_number((case when g.grade='DRP' then '5.00' else g.grade end), '9D99') * s.subjunits)))/(SUM(s.subjunits)), 2)
I don't have a copy of Postgres handy so I can't test this, and I'm not familiar with the to_number function (it's been years since I used Postgres). But that's not the point of your question, so if that's not the correct way to call to_number, that's a different issue.
The CASE part is ok (although you miss an ELSE there, it should still work and optionally return NULL).
The error is caused by the TO_NUMBER() function.

mysql complex select query from multiple tables

Table Visits;
fields[id,patient_id(fk),doctor_id(fk),flag(Xfk),type(Xfk),time_booked,date,...]
Xfk = it refer to other table, but its not a must to exist so i dont use constrain.
SELECT `v`.`date`, `v`.`time_booked`, `v`.`stats`, `p`.`name` as pt_name,
`d`.`name` as dr_name, `f`.`name` as flag_name, `f`.`color` as flag_color,
`vt`.`name` as type, `vt`.`color` as type_color
FROM (`visits` v, `users` p, `users` d, `flags` f, `visit_types` vt)
WHERE `p`.`id`=`v`.`patient_id`
AND `d`.`id`=`v`.`doctor_id`
AND `v`.`flag`=`f`.`id`
AND `v`.`type`=`vt`.`id`
AND `v`.`date` >= '2013-02-27'
AND (v.date <= DATE_ADD('2013-02-27', INTERVAL 7 DAY))
AND (`v`.`doctor_id`='00002' OR `v`.`doctor_id`='00001')
ORDER BY `v`.`date` ASC, `v`.`time_booked` ASC;
One big statmeant i have !
my question is,
1: should i consider using join instead of select multiple tables ?
and if i should why ?
this query execution time is 0.0009 so i think its fine, and since i get all my data in one query, or is it bad practice ?
2: in the select part i want to say
if v.type != 0 select f.name,f.color else i dont want to select them nither there tables flags f
is it possible ?
also currently if flag was not found, it replicate all rows as much as flag table have in rows ! is there a way i can prevent this ? both for
flag and visit_types table ?
If it's running fast, I wouldn't mess with it. I generally prefer to use joins instead of matching stuff in the where clause.
Any chance you'd remove the ` characters? Just makes it a bit harder to read in my opinion.
Look at the case statement for MySQL: http://dev.mysql.com/doc/refman/5.0/en/case.html
select case when v.type <> 0 then
f.name
else
''
end as name, ...

Using a bit input in stored procedure to determine how to filter results in the where clause

I'm beating my head against the wall here... can't figure out a way to pull this off.
Here's my setup:
My table has a column for the date something was completed. If it was never completed, the field is null. Simple enough.
On the front end, I have a checkbox that defaults to "Only show incomplete entries". When only pulling incomplete entries, it's easy.
SELECT
*
FROM Sometable
WHERE Completed_Date IS NULL
But offering the checkbox option complicates things a great deal. My checkbox inputs a bit value: 1=only show incomplete, 0=show all.
The problem is, I can't use a CASE statement within the where clause, because an actual value uses "=" to compare, and checking null uses "IS". For example:
SELECT
*
FROM Sometable
WHERE Completed_Date IS <---- invalid syntax
CASE WHEN
...
END
SELECT
*
FROM Sometable
WHERE Completed_Date =
CASE WHEN #OnlyIncomplete = 1 THEN
NULL <----- this translates to "WHERE Completed_Date = NULL", which won't work.. I have to use "IS NULL"
...
END
Any idea how to accomplish this seemly easy task? I'm stumped... thanks.
...
WHERE #OnlyIncomplete = 0
OR (#OnlyIncomplete = 1 AND Completed_Date IS NULL)
Hmmm... I think what you want is this:
SELECT
*
FROM Sometable
WHERE Completed_Date IS NULL OR (#OnlyIncomplete = 0)
So that'll show Date=NULL plus, if OnlyIncomplete=0, Date != Null. Yeah, I think that's it.
If you still want to use a CASE function (although it may be overkill in this case) :
SELECT
*
FROM Sometable
WHERE 1 =
(CASE WHEN #OnlyIncomplete = 0 THEN 1
WHEN #OnlyIncomplete = 1 AND Completed_Date IS NULL THEN 1
END)

How do I handle Error in sql queries?

For sql queries like..
select Quantity_Books/datepart(hour,Rent_Hour) from Rent_Book where (some conditions..)
They will return error when datepart(hour,Rent_Hour) is 0.
If sth like that Happens, I would like to show 0.
I know I should use case when But I am not really sure how..
Or any other better method?
You'd simply test the value first
select
CASE
WHEN datepart(hour,Rent_Hour) = 0 THEN 0
ELSE Quantity_Books/datepart(hour,Rent_Hour)
END
from
Rent_Book where (some conditions..)
Alternatively, use NULL rules
ISNULL((Quantity_Books / (NULLIF(datepart(hour,Rent_Hour), 0))), 0)
select case when datepart(hour,Rent_Hour)<>0 then Quantity_Books/datepart(hour,Rent_Hour) else 0 end as col ...

Resources