I am a beginner programmer wanna ask about simple SUM query for C#. here is the case:
I have a table called "revenue", and that table consist of 5 columns. they are Bulan, Target, Realisasi, Target_YtD, and Realisasi_YtD. for column Bulan, I manually inserted 12 data. they are January, Februari, March, and so on...
For column Target and Realisasi also I inserted data manually with INT data type.
Now, I wanna add up the January's Target + February's Target + March's Target, and then the value of that calculation is gonna fill March's Target_YtD.
Can somebody tell me the query of that? I hope anyone can help me this time, I really appreciate that. Thanks
Do you mean something like this?
UPDATE
SET Target_YtD =
(SELECT SUM(Target) AS Total FROM revenue
WHERE Bulan IN ('JAnuary', 'February', 'March')
)
WHERE Bulan = 'March'
It depends on if you plan to calculate the colum at the time of input and save it to the database. Usually calculated columns are not in and of themselves columns in databases, but if that is what you are doing you can just use the c# concatenation function to populate that variable before doing your insert statement. If you're only populating the sum upon output to a c# app, same thing applies, or you could do a sum in your sql code. A few ways to get there, just depends what you're trying to do.
Related
This is my first time using c# and sql server to code a simple monthly reporting application which will print the report to paper.
Everything just fine but there is a complicated problem for me when comparing two value.
Suppose there are 14 columns(originally 37 columns) and 12 rows for each month. The last column i am using for month name.
Columns are:
Name, col2,col3,col4,col5,col6,col7,col8,col9,col10,col11,monthName.
Logically there will be 12 reports in a year.
col2+col5+col6
and
col7+col10+col11 sum of current month's
must be same as last month col4 and col9-12 rows
This is my main problem!
For example if monthName has January(as past month) and I am filling the current month February . There is a pushButton called "Verify".
If I click on verify then the February's 3 columns sum will be compared to January's 1 column sum as above.
I have tried some sql query like select * from table1 where sum(col4)=sum(col2+col5+col6) and sum(col9)=sum(col7+col10+col11)
But my logic and knowledge is completely flawed since it did not work as expected.
Secondly, I thought appending data from sql query results to List<> and comparing the col4/col9 would be an idea but again flawed as there is no gurantee that Name column's value would not be shuffled which will lead to compare to wrong data, also I am not confident at it.
I need help from c# and sql database expert to get an idea to do this as I am not sure what is my options!
Update: I am doing some experiment in visual studio. All codes are just ugly but i will upload it on dropbox if someone care to try it.
I think your best solution here is to keep the business logic and the database query separate. If the user clicks the "verify" button on the "February" row, you just submit a database query along the lines of SELECT * FROM table1 WHERE monthName = 'january' although:
Probably you should actually use a date field to identify your months).
How you actually retrieve the data will depend on what type of data access you are using (ADO.NET, Entity Framework, etc.)
Once you get back that result, you just use straightforward C# logic to do the verification, along the lines of:
int priorMonthSum1 = priorMonthResultset.col4;
int priorMonthSum2 = priorMonthResultset.col9 + priorMonthResultset.col10 + priorMonthResultset.col11 + priorMonthResultset.col12;
int currentMonthSum1 = currentMonthResultset.col2 + currentMonthResultset.col5 + currentMonthResultset.col6;
int currentMonthSum2 = currentMonthResultset.col7 + currentMonthResultset.col10 + currentMonthResultset.col1;
if(priorMonthSum1 != currentMonthSum1 || priorMonthSum2 != currentMonthSum2)
{
// handle mismatch (highlight red?)
}
else
{
// handle match (highlight green?)
}
I have a data table
and it contains some int type columns, some type double columns, some date type columns
what i am trying to do is,
i want to do double.TryParse for double column, and if there is any value with it then it will store dbnull value in corresponding rows,
same thing i will do for date, int
since my data table could have 100000 records so i don't to run loop for each row
is it possible through linq or with any method
Thank You
LINQ is not good for batch operations. You should create a stored procedure in your DB and import it in your model (If you are using EF that is import function, if using LINQ to SQL then a simple drag and drop will do it).
LINQ is no silver bullet for all problems where you need to loop over a (maybe very large) set of data. So if you want to go over each data set and change the values depending on some condition, a foreach loop is your friend.
LINQ is a query language to retrieve data and not some kind of super-fast way to alter large lists or other enumerable objects. It comes in handy if you want to get data from a given object applying some conditions or doing a GroupBy without ending up in a 20-lines unreadable mash of foreach-loops and if-statements.
It doesn't matter if you'll do it in a loop or with linq, you'll still need to iterate over the entire data table ...
there's no silver bullet that will save you from doing the checks and inserts i'm afraid
I want to total the values of 2 columns (MilesLadenToll, MilesLadenNonToll) from a table (FuelTaxTripSummary) based on my query (see select statement below).
I am new to C# and have only been able to display query results in DataGridView and get a total for some columns and then display the total in a text box. I would like to simply display the totals without having to list all the query results in a DataGrid View. What is the best way of doing this?
I would really appreciate examples of working code, since I new to C# and SQL.
My connection string is stored in a global variable:
dbSettings.dbConnString
Example of my select statement is:
select MilesLadenToll, MilesLadenNonToll
from FuelTaxTripSummary
where WorkMonth >= '10/01/2011' and WorkMonth < '01/01/2012'
Thanks :-)
You can take advantage of SQL aggregate functions. The SUM function can be particularly useful:
SELECT
SUM(MilesLadenToll) as MilesLadenTollTotal,
SUM(MilesLadenNonToll) as MilesLadenNonTollTotal
FROM FuelTaxTripSummary
WHERE WorkMonth >= '10/01/2011' and WorkMonth < '01/01/2012'
This query will provide a single result row with both totals.
As to how to populate the Label with the results of the query, I'm completely unfamiliar to C#, but take a look at How to add text to a WPF Label in code? and at the accepted answer to the following almost duplicate question C# SQL SUM value to a label.
You should probably be using executeReader instead of executeScalar in order to get each one of the totals, as suggested in How to populate more than one column using executescalar?
I'm trying to write a stored procedure in SQL Server that will eliminate some logic in my C# program. What I'm doing right now is the query is in a view. Then I'm making a list with the view.
List<MyView> listOrdered = new List<MyView>();
Here's where it gets hairy. The query returns rows that are duplicates. I don't want to delete the duplicate rows I want to combine them into 1 row. The rows are identical except for 1 column.
Example:
UID Name Age Child
1 John 50 Sally
1 John 50 Steve
2 Joseph 42 Timmy
2 Joseph 42 Billy
So what I'm doing in C# is writing logic that says: (pseudo code)
foreach(item in list)
{
if (UID != UIDCurrent)
{
Build Row
AppendRow to list
}
else
{
Append Child Column to Current Child Column
}
}
Basically it gives me:
UID Name Age Children
1 John 50 Sally, Steve
But instead of doing this logic in C# I would like to do this a stored procedure. So how I can I get SQL Server to combine the children column for each row instead of multiple rows.
If you need anything else to help you help me I will respond.
Oh guys believe me I don't want to do it this way either. The Database I'm using is huge and complex and doing this with C# was sensible and works but I've been asked to turn my function that does this in C# into a stored procedure. I just want to see if this is even possible.
This demonstrates a poor table design. Fix it at the root and then you don't have this silly logic in either your db or C# code.
instead of
people(UID, Name, Age, Child)
try
people(UID, Name, DateOfBirth)
children(Parent references people.UID, child references people.UID)
You can leave age instead of moving to date of birth but it's really a much better idea to do it this way.
This should work if you want to do this in the database, though you should think about doing it in the front-end.
SELECT UID,
Name,
Age,
STUFF(
(SELECT ',' + Child AS [text()]
FROM parentChildren b
WHERE a.UID = b.UID
FOR XML PATH('')),1,1,'') [ChildConcat]
FROM parentChildren a
This is 100%, without a doubt something to be handled in your application code, NOT in the database!
SQL performs fairly poorly in string manipulation operations, especially compared to iterative languages like C#. You want your database to pass you the actual DATA, and then how you display that to be handled in the application layer.
Any attempt to solve this in SQL will be slower and harder to maintain than a version in your application code.
I have a table, and it has the Columns Quantity, Price and LineTotal. When I add something to the Cart, I add the Quantity and the Price of the product, and when the user visits the Cart page to view their cart, I want to re-calculate the LineTotal when they update the quantities for the items they've selected.
Now, my question is, should I re-calculate the LineTotal of each item in the cart using SQL (and if so, how?) or, should I do it in C# (And if so, what would be the best way to go about this?) To my surprise, I can't really seem to find anything on calculations in SQL - other than forums where people talk about it, but I have yet to see any code or documentation.
You should be able to use the arithmetic operators within SQL to generate your line totals. Reference here.
Well if you wanted to you could change the LineTotal column to a computed column but there's nothing stopping you from doing it in C# before the Insert/update
Since it seems to be a fairly simple calculation its tough to really strongly go with one or the other, and its mostly up to preference
Computed Column sample
ALTER TABLE dbo.YourTable
ADD LineTotalComputed AS (Quantity * Price) PERSISTED