greater than or less than with an amount - sql

Sorry if this is basic but couldn't find this anywhere on stack overflow.
Ive created a temporary table and when i run the query it brings back alot of results. I need to narrow it down further by an amount difference between the 2 columns but im struggling to work out how to do it. The current query is:
select * from #mi where round(avalue,0) <> round(bvalue,0)
I basically want it to say <> 1000 (amounts are not the same but there is 1000 difference between the amounts i want to view)
Currently i am getting figures like this
avalue=10000 bvalue=10000.1
I need it to show as
avalue=10000 bvalue=20001 or bvalue=8999
Thanks

Your question is a little unclear. I think it is:
amounts are not the same but there is 1000 difference between the amounts i want to view
Use - and `abs():
select *
from #mi
where abs(a.value - b.value) < 1000

you can use case when
select t.*,
case when round(avalue,0) <> round(bvalue,0) then round(bvalue+bvalue+1,0)
from #mi t

Related

Scalar subqueries produced more than one element

I know this error has been produced many time and a lot of answers came by but I believe every situation might be unique.
So i am trying to get a deficit value(imports - exports) from a table. Both values are on one column
value account
100 export
200 import
SO now i need to calculate the deficit or surplus, which is either import-export or export-import. I tried scalar subqueries but i am always getting this error.
SELECT label, product_type,status,((select value from Task2.quarterly_report where account="Imports") - (select value from Task2.quarterly_report where account="Exports")) As trade_deficit
so basically i am trying to get a table with:-
label product_type status trade_deficit
Can anyone explain to me the issue and why is it happening and how to solve it.
Thanks in advance
You can use the conditional aggregation:
select sum(case when account = 'import' then value
when account = 'export' then - value
end)
from t;
This is based on the question and sample data. I don't see what your query has to do with the rest of the question.

Failed UPDATE with CASE

I'm trying to write a query which will update reorder_level based on how much of an item was sold within a particular time period.
with a as (select invoice_itemized.itemnum, inventory.itemname,
sum(invoice_itemized.quantity) as sold
from invoice_itemized
join inventory on invoice_itemized.itemnum=inventory.itemnum and
inventory.vendor_number='COR' and inventory.dept_id='cigs'
join invoice_totals on
invoice_itemized.invoice_number=invoice_totals.invoice_number and
invoice_totals.datetime>=dateadd(month,-1,getdate())
group by invoice_itemized.itemnum, inventory.itemname)
update inventory
set reorder_level = case when a.sold/numpervencase>=5 then 30
when a.sold/numpervencase>=2 then 20
when a.sold/numpervencase>=1 then 5
else 1 end,
reorder_quantity = 1
from a
join inventory_vendors on a.itemnum=inventory_vendors.itemnum
Replacing the update with a select performs entirely as expected, returning proper results from the case and selecting 94 rows.
with the update in place, all of the areas affected by the update (6758) got set to 1.
Run this, and eyeball the results:
with a as (select invoice_itemized.itemnum, inventory.itemname,
sum(invoice_itemized.quantity) as sold
from invoice_itemized
join inventory on invoice_itemized.itemnum=inventory.itemnum and
inventory.vendor_number='COR' and inventory.dept_id='cigs'
join invoice_totals on
invoice_itemized.invoice_number=invoice_totals.invoice_number and
invoice_totals.datetime>=dateadd(month,-1,getdate())
group by invoice_itemized.itemnum, inventory.itemname)
select a.sold, numpervencase, a.sold/numpervencase,
case
when a.sold/numpervencase>=5 then 30
when a.sold/numpervencase>=2 then 20
when a.sold/numpervencase>=1 then 5
else 1
end,
*
from a
join inventory_vendors on a.itemnum=inventory_vendors.itemnum
Always a good idea to select before update to check that data ends up as you expect
all of the areas affected by the update got set to 1
I put the raw ingredients into the query above; see if the sums worked out as expected. You might need to cast one of the operands to something with decimal places:
1/2 = 0
1.0/2 = 0.5
And it updated far more rows than i was expecting
Every row that comes out of that select will be updated. Identify the rows you don't want to update and put a where clause in to remove them
Am i overthinking this?
Undertesting, probably
Do I even need the cte?
Makes it easier to represent, but no- you could get the same result by pasting the contents of the cte in as a subquery.. it's what the db does (effectively) anyway
Do i have my from statement in the wrong place?
We don't know what result you're after so that one is impossible to answe beyond "doing so would probably generate a syntax error, so.. no"
The actual problem seems to be
your case when is always going to ELSE, find out why
your cte selects too many rows (I couldn't tell if the number you posted was the number you got or the number you were expecting but it's pretty moot without example data), find out why
Solved. When I added another join to the update it worked correctly. i had to add join inventory on inventory_vendors.itemnum=inventory.itemnum

SQL Sub-Query Troubles

I have a SQL assignment I am working on for school (just a series of query and sub-query questions) and I have them all complete but one. Here is the prompt for reference:
10. Find the AM hours with total traffic load with 200 or more.
I have the code for the first part, the AM hours. It is as such:
select hour(traffic.ttime), sum(traffic.packetsize)
from traffic
where hour(traffic.ttime) <= 12
group by hour(traffic.ttime);
The only thing I cant figure out is how to get only the ones with 200 or more. It should return only 3 rows but regardless of what I try it still returns all or non. I'm pretty sure a sub-query needs to be used here but I cant seem to figure it out. This is what I have tried so far:
select hour(traffic.ttime), sum(traffic.packetsize)
from traffic
where hour(traffic.ttime) <= 12 and (select sum(traffic.packetsize) from
traffic)>=200
group by hour(traffic.ttime) ;
Logically I know that is incorrect due to the fact that it will just return the sum of all the packet sizes in that given table. I cant seem to come up with anyway to make it work without it throwing an error. Any help would be appreciated!
select hour(traffic.ttime), sum(traffic.packetsize)from traffic where hour(traffic.ttime) <= 12 group by hour(traffic.ttime) having sum(traffic.packetsize)>=200

How to accurately figure percentage of a finite total

I’m in the process of creating a report that will tell end users what percentage of a gridview (the total number of records is a finite number) has been completed in a given month. I have a gridview with records that I’ve imported and users have to go into each record and update a couple of fields. I’m attempting to create a report tell me what percentage of the grand total of records was completed in a given month. All I need is the percentage. The grand total is (for this example) is 2000.
I’m not sure if the actual gridview information/code is needed here but if it does, let me know and I’ll add it.
The problem is that I have been able to calculate the percentage total but when its displayed the percentage total is repeated for every single line in the table. I’m scratching my head on how to make this result appear only once.
Right now here’s what I have for my SQL code (I use nvarchar because we import from many non windows systems and get all sorts of extra characters and added spaces to our information):
Declare #DateCount nvarchar(max);
Declare #DivNumber decimal(5,1);
SET #DivNumber = (.01 * 2541);
SET #DateCount = (SELECT (Count(date_record_entered) FROM dbo.tablename WHERE date_record_entered IS NOT NULL and date_record_entered >= 20131201 AND date_record_entered <= 20131231);
SELECT CAST(ROUND(#DivNumber / #DateCount, 1) AS decimal(5,1) FROM dbo.tablename
Let’s say for this example the total number of records in the date_record_entered for the month of December is 500.
I’ve tried the smaller pieces of code separately with no success. This is the most recent thing I’ve tried.
I know I'm missing something simple here but I'm not sure what.
::edit::
What I'm looking for as the expected result of my query is to have a percentage represented of records modified in a given month. If 500 records were done that would be 25%. I just want to have the 25 (and trainling decimal(s) when it applies) showing once and not 25 showing for every row in this table.
The following query should provide what you are looking for:
Declare #DivNumber decimal(5,1);
SET #DivNumber = (.01 * 2541);
SELECT
CAST(ROUND(#DivNumber / Count(date_record_entered), 1) AS decimal(5,1))
FROM dbo.tablename
WHERE date_record_entered IS NOT NULL
and date_record_entered >= 20131201
AND date_record_entered <= 20131231
Why do you select the constant value cast(round(#divNumber / #DateCount, 1) as decimal(5,1)from the table? That's the cause of your problem.
I'm not too familiar with sql server, but you might try to just select without a from clause.
select emp.Natinality_Id,mstn.Title as Nationality,count(emp.Employee_Id) as Employee_Count,
count(emp.Employee_Id)* 100.0 /nullif(sum(count(*)) over(),0) as Nationality_Percentage
FROM Employee as emp
left join Mst_Natinality as mstn on mstn.Natinality_Id = emp.Natinality_Id
where
emp.Is_Deleted='false'
group by emp.Natinality_Id,mstn.Title

INTERSECT not acting as I expect

I'm not sure if this is a symptom of my relative inexperience with SQL, or with h2. I have a view, called VIEW_TRANSACTION_LEGS_DATA, which I need to search in various ways. So, for example, I have:
SELECT HEAD_ID FROM VIEW_TRANSACTION_LEGS_DATA WHERE AMOUNT > 1000
and I also have:
SELECT * FROM
(SELECT HEAD_ID FROM VIEW_TRANSACTION_LEGS_DATA WHERE AMOUNT > 1000)
INTERSECT
(SELECT HEAD_ID FROM VIEW_TRANSACTION_LEGS_DATA WHERE AMOUNT < 2000)
Unfortunately, this isn't working as I expect! There should only be 3 rows returned, whereas I am getting 57 returned.
(Note that the above is a simplified version of what my code actually says; please don't suggest to me to combine the INTERSECTed lines using a BETWEEN since this will not work with the rest of the code.)
I'm sure my problem is a typical SQL newbie type problem, but I simply can't see it! Can some kind person please point me in the right direction?