Dsum with Null Value - ms-access

I am having abit of a situation and hope you can point me at the right direction.
1st DSUM (Text2):
=DSum("[quantity_ya7]","Stock","[part_number]= '" & [part_number] & "'")
2nd DSUM (Text2): (This can be Null at times as there are no withdrawals or records)
=DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' ")
After setting the 2 DSUM above, I will carry the subtract out.
=Text1-Text2
If there are values for to calculate for 2nd DSUM, the result will display in order. Else, it will be empty. (No values displayed)
How do I calculate as -0 (deduct 0) so I can get the right value displayed?
Thank you, much appreciated.

You can use the Nz function to return zero, a zero-length string ("
"), or another specified value when a Variant is Null. For example,
you can use this function to convert a Null value to another value and
prevent it from propagating through an expression.
https://support.office.com/en-gb/article/Nz-Function-8ef85549-cc9c-438b-860a-7fd9f4c69b6c
In your case you want the DSUM to return 0 rather than Null when there's no value so you can use it in a calculation.
=NZ(DSum("[amt_ya7]","Withdrawal","[part_number]= '" & [part_number] & "' "),0)

Related

SSRS Textbox expression filter from Dataset

Trying to create a TextBox expression:
="Validity: " & IIF(Fields!ID.Value = 2, Fields!Value.Value, "") & " from date above."
from a dataset:
ID; NAME; VALUE;
1; Delivery; x Factory;
2; Validity; 30 days;
3; Pricing Structure; Subject to...;
so that the text box would read "Validity: 30 days from date above" but returns "Validity: from date above"
The problem is the report only allows me to use aggregate First, max, etc from the dataset producing an incorrect result.
"Validity: " & IIF(First(Fields!ID.Value, "DataSet") = 1, First(Fields!Value.Value, ), "") & " from date above."
"Validity: x Factory from date above"
Your dataset is showing "30 days", do you require the text box to show this or do you require it to be "60 days"?
Meanwhile if you restrict you dataset to one row of data, ie insert a where/having clause such as : HAVING (ID = 2), then you could use the aggregate sum function in your expression:
="Validity: " & IIF(Sum(Fields!ID.Value, "DataSet1") = 2, Fields!Value.Value, "") & " from date above."

Mysql query not inserting values

I am trying to use the query below to insert a concatenated converted set of integers to string for use on a datetime field in my table.
TABLE
Field Type
empID int(11)
time_stamp datetime
in_out char(3)
am_pm char(2)
QUERY
Dim query As String = "INSERT INTO attendance VALUES(" & empID.Text & _
"STR_TO_DATE(CONCAT("& empYear.Text & ",'-'," & empMonth.Text & ",'-'," & _
empDay.Text & ",' '," & empHour.Text & ",':'," & empMin.Text & ",':'," & _
empSec.Text & ",'%Y-%m-%d %H:%i:%s'),'out','pm')"
There is no problem with the connection and the values. I have tried to insert the values into a test column of string type and the output is this:
133201712311827
I am pretty sure it's with how I use these characters: '' "" "," - :. I just can't figure out how.
First problem I see, here
& empID.Text & "STR_TO_DATE(. . . .
you're missing comma after first value
& empID.Text & "***,*** STR_TO_DATE(. . . .
Second issue, I identified when I've replaced your text values with hard coded values - You are missing closing parenthesis for str_to_date. Here ,'%Y-%m-%d... should be ), '%Y-%m-%d...
STR_TO_DATE(CONCAT(1999,'-',01,'-',01,' ',10,':',25,':',30***)***,'%Y-%m-%d %H:%i:%s')
As you see- my replacement shows that you have no issues with concatenation, single quote and :. Theo only other variable here is quality of data in text boxes.
Update
This answer (above) is correct. Using sql fiddle I created schema and when replaced text box values with hard-coded ones - all worked. My suggestions to add comma and parenthesis hold true. Your claim about problems with single quotes are false.
create table xxx (empID int(11), time_stamp datetime, in_out char(3), am_pm char(2));
INSERT INTO xxx VALUES(123,
STR_TO_DATE(CONCAT('2017','-','1','-','23',' ','10',':','35',':','40'),'%Y-%m-%d %H:%i:%s'),
'out','pm');
commit;
Select * from xxx
empID | time_stamp | in_out | am_pm
123 | January, 23 2017 10:35:40 | out | pm
End Update
On top of that, you could do it much better by parameterizing, which will look like something like this
command.CommandText = "insert into ... values (#1, #2, #3, #4)"
command.Parameters.AddWithValue("#1", Convert.ToInt32(empID.Text))
dim date as new DateTime(Convert.ToInt32(empYear.Text), Convert.ToInt32(empMonth.Text), . . . . )
command.Parameters.AddWithValue("#2", date)
. . . . . .
command.ExecuteNonQuery()
Parameterizing will make it easy to work with dates and strings

Inserting values starting with zero in access database

I have a field called Product_Id(type string), which has length of 7 and starting with 0. But while inserting through VBA into a table field of type text the zeros is not getting inserted.
This is the insert query:
dbs.Execute "INSERT INTO tablename (PROD_NBR)VALUES (" & prodID & ");"
I think I have fixed the error - you need to declare the value in single quotes.
The PROD_NBR is a string type and field in the table is text type, then the inserting variable should be declared inside single quotes then double quotes and between two & symbols:
dbs.Execute "INSERT INTO tablename (PROD_NBR)VALUES ('" & prodID & "');"
Responding to #Cherry's answer, the following method is less tedious than a parameterized query, aka prepared statement. prodID can safely contain quotes and other special characters.
With dbs.OpenRecordset("tablename")
.AddNew
.Fields("PROD_NBR") = prodID
.Update
End With
Regarding the "starting with zero" part of your question, do you want PROD_NBR to always be 7 characters, padded with leading 0's? Then replace prodID with:
Right("0000000" & prodID, 7)

SELECT Between dates almost working

My problem is likely all about date formatting in a SELECT.
In an asp file I open an ADO Recordset wanting to retrieve rows of a MS SQL table that fall between date1 (08/15/2013) and date2 (08/22/2013) (i.e., the previous 7 days from today's date.)
The SELECT does retrieve the appropriate 2013 rows but also retrieves rows going back to 08/15/2012.
Here is the SELECT:
oRS.Source = "SELECT * FROM aTable WHERE entry_Date BETWEEN '" & resultLowerDate & "' AND '" & resultCurrentDate & "' AND entry_Status <> 'INACTIVE'"
resultLowerDate = 08/15/2013 and resultCurrentDate = 08/22/2013.
The table is set up as follows with resultCurrentDate = "08/22/2013":
entry_Status entry_Date (varchar) LastName FirstName SELECT Result
INITIAL 08/15/2012 Smith Jim YES
INACTIVE 08/21/2012 Green Tom no
INITIAL 08/22/2013 Jones Mary yes
FOLLOWUP 08/22/2013 Jones Mary yes
FOLLOWUP 08/22/2013 Brown Sally yes
FOLLOWUP 08/22/2013 Smith Jim yes
Any thoughts as to why the INITIAL 08/15/2012 row gets selected along with the other rows that meet the SELECT query?
STOP STORING DATES IN VARCHAR COLUMNS! And STOP CONCATENATING STRINGS, USE PROPER PARAMETERS.
Sorry to yell, but we are getting multiple questions a day where people use the wrong data type for some unknown and probably silly reason, and these are the problems it leads to.
The problem here is that you are comparing strings. Try:
"... WHERE CONVERT(DATETIME, entry_date, 101)" & _
" >= CONVERT(DATETIME, '" & resultLowerDate & "', 101)" & _
" AND CONVERT(DATETIME, entry_date, 101)" & _
" < DATEADD(DAY, 1, CONVERT(DATETIME, '" & resultCurrentDate & "', 101))"
Or better yet, set resultLowerDate and resultUpperDate to YYYYMMDD format, then you can say:
"... WHERE CONVERT(DATETIME, entry_date, 101) >= '" & resultLowerDate & "'" & _
" AND CONVERT(DATETIME, entry_date, 101) < DATEADD(DAY, 1, '" & resultCurrentDate & "'"
Note that I use an open-ended range (>= and <) instead of BETWEEN, just in case some time slips into your VARCHAR column.
Also note that this query could fail because garbage got into your column. Which it can, because you chose the wrong data type. My real suggestion is to fix the table and use a DATE or DATETIME column.
The fact that your entry_Date column is a varchar field and not an actual date is the problem. If you cast it to a datetime during the select, you'll get the results you expect.
select *
from aTable
where cast(entry_Date as datetime) between '08/15/2013' and '08/22/2013'
Sql Fiddle link

Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values?

I am interested to know that Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values?
Like in my below code, I have order_primary column which contains order no. so based on that we can identify how many products belongs to particular order. Also count is for storing those values like 1,2,3 etc.
But I am facing problem that count value is just going incrementaing...
My code-:
$query_product = "SELECT name, id,qty_ordered,price,row_total,base_subtotal,
base_shipping_amount,base_grand_total,order_primary,message
FROM sales_order WHERE `prod_Flag`=0 ";
$result_query_product = mysql_query($query_product);
$count = 0;
while($row = mysql_fetch_array($result_query_product))
{
$count++;
$name = ($row["name"]);
$message1 = ($row["message"]);
$result_str_product .= "('". mysql_real_escape_string($name) . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"] . "',". "'" . $row["price"] . "'," . "'" . $row["row_total"] . "'," . "'" . $row["base_subtotal"]. "'," . "'" . $row["base_shipping_amount"] . "'," . "'" . $row["base_grand_total"] ."',". $row["order_primary"].",". $count.",". "'".mysql_real_escape_string($message1)."'".", NOW()),";
}
$query_prod_insert = "INSERT into sales_product(name, sku, qty_ordered, price, row_total, base_subtotal, base_shipping_amount,base_grand_total,prod_foreign,count,message,product_creation_date) VALUES ".$result_str_product;
$final_query = substr_replace($query_prod_insert,";",-1);
$result_query_product_outbound = mysql_query($final_query);
So My o/p is-:
('shirt','st','2.0000','75','150','150','20','170',29,1,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,2,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,3,NOW()),
('socks','sk','5.0000','20','100','100','05','105',30,4,NOW());
('jackt','jt','3.0000','40','120','120','15','135',30,5,NOW());
But I want o/p like this-:
('shirt','st','2.0000','75','150','150','20','170',29,**1**,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,**2**,NOW()),
('tie' ,'te','2.0000','50','100','100','10','110',29,**3**,NOW()),
('socks','sk','5.0000','20','100','100','05','105',30,**1**,NOW());
('jackt','jt','3.0000','40','120','120','15','135',30,**2**,NOW());
So Is there any mysql/Oracle function to give incremental no. to one column on the basis of another columns of similar values i.e. in my case, for same order no. value say 29, count values should be 1,2,3 & for same order no. 30, count value should be 1,2...
So is there any function or how to do the same.
For Oracle this is pretty easy:
SELECT order_no,
row_number() over (partition by order_no order by order_primary) as rn
FROM sales_product
Note: I'm guessing the column names as they are somewhere hidden in the PHP(?) code. Please adjust them according to your table structure. For future posts you should also include the corresponding CREATE TABLE statement in your question.