I have dwelling on this for hours and still cannot find out how to do this. How do you get the total sales of an item for every year.
What I have got so far is this:
SQLCommand.CommandText = #"SELECT SUM SalesNo AS TotalYearSales FROM SalesTable WHERE Product = " + ddItems.SelectedItem + "";.
The table headings are as follows Product, Year, SalesNo.
SQLCommand.CommandText = #"SELECT DatePart( YY, SalesDate ), SUM( SalesNo ) AS TotalYearSales FROM SalesTable WHERE Product = ? GROUP BY DatePart( YY, SalesDate ) ";
SQLCommand.Parameters.Add( "parmForProduct", ddItems.SelectedItem );
As Daniel pointed out, you would be wide open to sql-injection attacks and should parameterized queries.
To get total by year, you have to add the year as a basis of the query too. I don't know the "date" column in your table the transactions are based on, so you'll have to adjust. The "?" in the query is a "place-holder" for the parameter added immediately after.. And parameters should be added in the same order as listed in the query. Some SQL engines allow "named" parameters and use something like "#ProductIWant", and your parameter would use the same...
Since you are querying for only a specific product, that doesn't need to be in the list.. unless you wanted ALL products grouped by year.
Something Like
Select Year(SalesDate),Sum(SalesNo) From SalesTable where Product = "Navel Defluffer"
Group By Year(SalesDate)
and as #Daniel alluded to, use parameterised queries not string concatenation.
Related
Developing an application in C# using a MySQL database. It involves cows and their weights. When displaying the cows details in a table, I want to display all of the animal's details as well as their last weight.
I have two tables used for this: 'Cattle' and 'Weights'. Each animal has a unique ID and this ID is used as foreign key in weights table along with the date taken and what they weighed. Up to now the way I am doing it is getting the MAX(Date) in the weights table and using a left join however if animal wasn't weighed on that date then it won't be included. I could use each animals MAX(Weight) however some animals may drop in weight due to illness etc.
SELECT Cattle.TagNumber,
Cattle.HerdNumber,
Cattle.Breed,
Cattle.DOB,
Cattle.Group,
Weights.Weight
FROM Cattle
LEFT JOIN Weights ON Cattle.TagNumber = Weights.TagNumber
WHERE Cattle.Group = '" + group + "'
AND Date = '" + date.ToString("yyyy/MM/dd") + "'";
The above query is what I use when filtering the data by the animals group. I understand that I could go through each animal individually and get their MAX(Weight) however this severely hinders the performance.
If you select for the Max(Date) found on the join, instead of searching a specific Date (Where clause), you will always get the results. Not exactly sure if this is what is asked.
SELECT Cattle.TagNumber,
Cattle.HerdNumber,
Cattle.Breed,
Cattle.DOB,
Cattle.Group,
Weights.Weight,
MAX(Date)
FROM Cattle
LEFT JOIN Weights ON Cattle.TagNumber = Weights.TagNumber
WHERE Cattle.Group = '" + group + "'
Group by Cattle.TagNumber;
Edit
The query should also return values with no weights; you just need to filter the data. You can use Case (it might not work exactly as I wrote it, but something around that). There was the End missing; also you probably need to convert weight to a nvarchar (or what you chose), otherwise you will get an error when inserting weight in the column NAMECOLUMN
SELECT Cattle.TagNumber,
Cattle.HerdNumber,
Cattle.Breed,
Cattle.DOB,
Cattle.Group,
(Case when Weights.Weight is null then 'N/A' Else Convert(nvarchar(max),Weights.Weight) End) as NAMECOLUMN,
MAX(Date)
FROM Cattle
LEFT JOIN Weights ON Cattle.TagNumber = Weights.TagNumber
WHERE Cattle.Group = '" + group + "'
Group by Cattle.TagNumber;
I want to insert the date and month (which is in two datetimepicker) along with insert value select query.
I have five columns in my invoice table
Student_id, Amount, Fee_description, issue_date, month
I can insert the values for the first three columns but the remaining two are null for which I don't know where to put the datetimepicker value??
I take a datatimepicker for date and month in the design view of the form
insert into invoice (Student_id, Amount, Fee_description, issue_date, month)
select
student.Student_id,
Fee.Fee_Amount, Fee.fee_type
from
student
join
parent on student.father_nic = parent.father_nic
join
allocate_class on student.Student_id = allocate_class.Student_id
join
class on class.class_id = allocate_class.class_id
join
session on allocate_class.session_id = session.session_id
join
Fee on class.class_id = Fee.class_id
where
session.session_id = 1
and Fee.fee_type = 'Tution Fee'
and student.status = 'active'
Where to add that two that datetimpicker value in the above query?
Sure. It would look something like this:
var cmd = new SqlCommand("insert into invoice (
Student_id,
Amount,
Fee_description,
issue_date,
month
)
select student.Student_id
, Fee.Fee_Amount
, Fee.fee_type
, #issDat
, #mon
from ...", "conn str here");
cmd.Parameters.AddWithValue("#issDat", issueDateDateTimePicker.Value);
cmd.Parameters.AddWithValue("#mon", monthDateTimePicker.Value);
I've used AddWithValue to quickly explain the concept- google for a blog called "can we stop using AddWithValue already" for a long discussion on how to move away from it(it's reasonable in this context as it's not being used for filtering) but for now the concept I'm trying to relate is:
An sql statement can take a fixed value from you:
SELECT 'hello' FROM table
It can also take a fixed parameter you supply:
SELECT #pHello FROM table
Hence adding parameters and filing them with fixed values from your day time pickers (or datetime.Now or whatever) is fine, and what you should be doing to insert fixed values using an INSERT ... SELECT style statement
Side note, it isn't clear if month and issue date are related but if they're the same date then you don't need to store it twice- you can extract the month from a date at any point.
I have to make in c# a query with linq to sql. I can handle it in sql but in linq to
sql is the result not what I wanted to get.
So there is a table with:
a day, in datetime with date and time
and a kind of id
I have to count the ids for each date, the time isn't important. So the result
should be something like:
day: 2013-11-12 amountIDs: 4
People said to me, I can make a select new query and in this query I can set the day
and could count the ids, or I make a group by day. I read similar question, but it doesn't work in my case.
Could somebody help me?
I tried it with the statement below, but the days have to be grouped, so now the output is foreach datetime, like this
day: 12.12.2013 12:00:00 amountIDs: 1
day: 12.12.2013 12:10:10 amountIDs: 1
In sql I made this statement:
SELECT CONVERT(VARCHAR(20), data.dayandtime, 106) AS day, count(data.amountIds) as ids
FROM data
WHERE ( data.dayandtime >= DATEADD(day, -28, getdate()) AND (data.type = 100) AND (data.isSomething = 0) )
GROUP BY CONVERT(VARCHAR(20), data.dayandtime, 106), data.isSomthing and it works.
I saw similar cases, where people made a : from-select-new xyz statement, than I made a view of it and tried to group just the view. Like this
var query = data.GroupBy(g => g.day.Value).ToList();
var qry = from data in dbContext
group data by data.day into dataGrpd
select new
{
day= dataGrpd.Key,
amountIDs= dataGrpd.Select(x => x.Id).Distinct().Count()
};
Check This
I want to write sql Query for unknown number of keywords. The keywords (tags) are stored in table like this
column1 column2
item1 tag1
item1 tag2
item1 tag3
. .
. .
. .
Now the user can enter any number of keywords to search against the table. if the and is used it will do strict search. if I use or it will search items that match only one keyword. I want query that dynamically shape itself and use maximum keywords given in the search if not all of them.
Like a Vehicle is the item and It has the keywords. Car, Vehicle, conveyance, Cycle, Bike, truck. Now I want to enter the keywords Bike Cycle in the textbox so it should form the query to search the vehicle item.
You can do a search with an OR operators or an equivalent IN (...) expression, group the rows by the item column, and compare row counts. The row with the highest count has the highest number of keywords from your search list:
SELECT TOP 1
column1, COUNT(*)
FROM mytable
WHERE column2 IN ('tag1', 'tag3')
GROUP BY column1
ORDER BY COUNT(*) DESC
To deal with lots of keywords without exposing your code to SQL injection you need to either generate your SQL dynamically, or use table-valued parameters.
If you take the first approach, the IN expression becomes IN (#tag0, #tag1, #tag2) up to the number of tags in your search string. Create a SQL command, and add individual tags as parameters. See this answer for more details on the dynamic query approach.
If the list of tags grows significantly, an alternative approach with a table-valued parameter could improve performance of your query. This answer explains how to do that.
Well with linq that would be something like (assuming you have a model class called Products) and the user has send an array of keywords
IQueryable<Product> SearchProducts (params string[] keywords)
{
IQueryable<Product> query = dataContext.Products;
foreach (string keyword in keywords)
{
string temp = keyword;
query = query.Where (p => p.Description.Contains (temp));
}
return query;
}
For more elaborate scenarios look at
http://www.albahari.com/nutshell/predicatebuilder.aspx
Did you want this?
SELECT * FROM TABLE
WHERE x.Keywords in (Select * FROM ListOfWantedKeywords) --The list of wanted keywords is your dynamic search.
Are you looking for this?
And version:
SELECT
SRC.*
FROM SRC
WHERE NOT EXISTS (
SELECT TOP(1)
1
FROM (
VALUES
('xxx')
, ('yyy')
) AS KEYWORDS(Word)
WHERE SRC.col NOT LIKE '%' + Word + '%'
)
Or version:
SELECT
SRC.*
FROM SRC
WHERE EXISTS (
SELECT TOP(1)
1
FROM (
VALUES
('xxx')
, ('yyy')
) AS KEYWORDS(Word)
WHERE SRC.col LIKE '%' + Word + '%'
)
I'm trying to write a windows forms app in C# .Net 4 it connects to a SQL Server 2008 database and I want to Select highest number from a table where the number is stored as string!
string SQL = "select MAX(CONVERT(int, myField)) from myTable where myCode = '" + theCust + "'";
I have also tried Max(CAST(myField as Int)) in the select statement but both fail to return anything even though the Database has for the theCust two rows with 10001 and 10002. The Error i Get is "Enumeration yielded no results"
What am I doing wrong?
I'm using the in built System.Data.SqlClient and if I just do a
string SQL = "select myField from myTable where myCode = '" + theCust + "'";
it returns both numbers as strings. I know I could sort them in code but if the Database gets large that would not be a good approach!
I just tried it again with an int Field in the db and still got the same error! Is Max the wrong thing to be using?
You can try it like this:
SELECT TOP 1 CAST(MyColumn AS int) AS TheMax
FROM MyTable
ORDER BY TheMax DESC
So (using the sloppy method, always paramaterize!)
String sql = "SELECT TOP 1 CAST(MyColumn AS int) AS TheMax FROM MyTable WHERE MyParam = '" + param + "' ORDER BY TheMax Desc";
//Fill DataAdapter/DataReader etc.
Have this function in your database(s):
CREATE FUNCTION dbo.IsAllDigits (#MyString VARCHAR(8000))
RETURNS TABLE AS
RETURN (
SELECT CASE
WHEN #MyString NOT LIKE '%[^0-9]%'
THEN 1
ELSE 0
END AS IsAllDigits
)
because it's better than the in-build ISNUMERIC() in T-SQL.
Then you can use this query to get set of strings that convert to integer types without errors, and filter them like with TOP 1.
SELECT TOP 1 MyColumn AS TheMax
FROM MyTable
WHERE IsAllDigits(MyColumn)=1
ORDER BY MyColumn DESC