We have a date column in an database table. We need to check if the date occurs multiple times and add the sum of another column, called 'hours_remaining'.
For example on 30/11/2017 we have two tasks with 3 and 4 in the 'hours_remaining' column. We need to sum these values and plot to a Visual Studio chart.
Currently it plots the two values separately on the chart.
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM SprintTask INNER JOIN Sprint ON SprintTask.sprint_id = Sprint.Id WHERE Sprint.Id = #sid", con);
cmd.Parameters.AddWithValue("#sid", Request.QueryString["sid"]);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet st = new DataSet();
sda.Fill(st, "task_start_date");
Chart1.DataSource = st.Tables["task_start_date"];
Chart1.Series["Series1"].XValueMember = "task_start_date";
Chart1.Series["Series1"].YValueMembers = "hours_remaining";
this.Chart1.Titles.Add("This is a test chart ");
Chart1.Series["Series1"].ChartType = SeriesChartType.Line;
Chart1.Series["Series1"].IsValueShownAsLabel = true;
As #mjwills wrote in his comment, you need to use group by and sum:
SELECT task_start_date, SUM(hours_remaining) As hours_remaining
FROM SprintTask
INNER JOIN Sprint ON SprintTask.sprint_id = Sprint.Id
GROUP BY task_start_date
WHERE Sprint.Id = #sid
Related
I have two tables Repair_master and New_Equipment_info, with the query shown here, I am able to retrieve all the latest date record of maint. by grouping RID and fill the data grid.
SELECT
t1.RID
,t1.RDATE
,t1.EQ_ID
,new_equipment_info.Equipment_Name
,new_equipment_info.Complete_specification
,t1.DEPT
,t1.REPAIR_MAINT
,t1.ACTION_TAKEN
,t1.SAPRES
,t1.ATT_BY
,t1.[STATUS]
,t1.RNO
FROM
Equipment.dbo.REPAIR_MASTER t1
INNER JOIN
Equipment.dbo.new_EQUIPMENT_INFO
ON t1.EQ_ID = New_Equipment_info.Equipment_Id
INNER JOIN
(
SELECT
Eq_ID
,max(RDate) as MaxDate
FROM
Equipment.dbo.REPAIR_MASTER
group by
Eq_ID
) tm
ON t1.EQ_ID = tm.EQ_ID
and t1.RDATE = tm.MaxDate
WHERE
t1.Repair_Maint = 'maint.'
ORDER BY
t1.RDATE DESC
But I want to know the number of days from the last date filtered from query and current date.
Like this
DATEDIFF(day, MaxDate, GETDATE()) AS Difference)
Kindly advise
Further I want to enter number of days in text box and click button and show only those records having a difference greater than the value entered.
private void btnOverDue_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connString))
{
string p = "SELECT t1.[RID],t1.[RDATE],t1.[EQ_ID],new_equipment_info.Equipment_Name,new_equipment_info.Complete_specification," +
"t1.[DEPT],t1.[REPAIR_MAINT],t1.[ACTION_TAKEN],t1.[SAPRES],t1.[ATT_BY],t1.[STATUS],t1.[RNO]FROM([Equipment].[dbo].[REPAIR_MASTER] t1 inner join[Equipment].[dbo].new_EQUIPMENT_INFO ON " +
"t1.EQ_ID = New_Equipment_info.Equipment_Id inner join (select Eq_ID, max(RDate) as MaxDate FROM [Equipment].[dbo].[REPAIR_MASTER] group by Eq_ID) tm on t1.EQ_ID=tm.EQ_ID and t1.RDATE =tm.MaxDate)" +
"where t1.Repair_Maint='maint.' ORDER BY t1.RDATE desc";
SqlCommand cmd = new SqlCommand(p, con);
SqlDataAdapter dataadapter = new SqlDataAdapter(p, con);
DataSet ds = new DataSet();
dataadapter.Fill(ds, "Repair_master");
EquipGrid.DataSource = ds;
EquipGrid.DataMember = "Repair_master";
}
}
I am trying to sum weekly_slot according to Teacher_Name from GroupOdd dbtable, however I am getting 10 values for all row. Appreciate if can correct me. Beside that, how to update GroupOdd dbtable to sort according to larger sum_weekly_slot first?
Thanks.
cmd2 = new SQLiteCommand();
cmd2 = dbConnect.CreateCommand();
//cmd2.CommandText = "DELETE FROM GroupOdd";
//cmd2.ExecuteNonQuery();
cmd2.CommandText = "SELECT Sum(Weekly_Slot) AS Sum_Weekly_Slot FROM GroupOdd group by Teacher_Name";
DataTable dt2 = new DataTable();
SQLiteDataAdapter da2 = new SQLiteDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
//cmd.CommandText = "INSERT INTO GroupOdd (Teacher_Name, Standard, Subject, Weekly_Slot, Balance_Slot) VALUES (#Teacher_Name, #Standard, #Subject, #Weekly_Slot, #Balance_Slot)";
cmd2.CommandText = "UPDATE GroupOdd SET Sum_Weekly_Slot = #Sum_Weekly_Slot";
//cmd2.Parameters.AddWithValue("#Sum_Weekly_Slot", dr2["Sum(Weekly_Slot)"].ToString());
cmd2.Parameters.AddWithValue("#Sum_Weekly_Slot", dr2["Sum_Weekly_Slot"].ToString());
cmd2.ExecuteNonQuery();
}
All you need is a GROUP BY clause with the MAX aggregate function:
SELECT id, MAX(rev)
FROM YourTable
GROUP BY id
Than Update it accordingly.
IF
Sum(Weekly_Slot);
is not what u looking for
try
Count(Weekly_Slot)
SELECT Teacher_Name, Sum(Weekly_Slot) AS Sum_Weekly_Slot FROM GroupOdd
group by Teacher_Name order by Sum(Weekly_Slot) desc
Check the Teacher_Names are unique, else try to use an Id (TeacherId) for Teachers. The order by Sum(Weekly_Slot) desc should sort the table by largest first.
I need to get the rank, from a group of players by sorting using sql query.
i have the query.
query = #"SET #rank=0;
SELECT player_ID,player_name,HP,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC;"
the problem is i just need the specified player's rank from this query.
Since rank is generated using SQL, i can't use WHERE clause. That will one bring one player from DB, resulting one rank.
I tried to get all of them into a datatable and then filter the single value out of it.
con.Open();
MySqlDataAdapter dt = new MySqlDataAdapter();
DataTable tt = new DataTable();
string query = #"SET #rank=0;
SELECT player_ID,player_name,HP,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC;";
MySqlCommand cm1 = new MySqlCommand(query, con);
dt.SelectCommand = cm1;
dt.Fill(tt);
con.Close();
DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
foreach (DataRow dr in foundRows)
{
Label32.Text = dr["Rank"].ToString();
}
this is how my table looks
http://pastebin.com/7KWJ9bn3
any help is appreciated.
I'm a big proponent of not putting business logic in your SQL which it seems like your doing here. The below code is my updated version of your code which should be logically equivalent without having to do any calculation on the SQL side of things.
I'm not entirely sure what you are trying to achieve (is this example code?) so if you can provide more info I can refine this some more, but again this will do the exact same thing in a "better" fashion.
con.Open();
MySqlDataAdapter dt = new MySqlDataAdapter();
DataTable tt = new DataTable();
string query = #"SET #rank=0;
SELECT player_ID,player_name,HP
FROM player_profile ORDER BY HP DESC;";
MySqlCommand cm1 = new MySqlCommand(query, con);
dt.SelectCommand = cm1;
dt.Fill(tt);
con.Close();
DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
int count = 1;
foreach (DataRow dr in foundRows)
{
Label32.Text = count;//dr["Rank"].ToString();
count++;
}
What about selecting from the resulting table?
string query = #"SET #rank=0;
Select a.Rank from (SELECT player_ID,#rank:=#rank+1 As Rank
FROM player_profile ORDER BY HP DESC) a where player_ID=#1";
I got this error! When open crystal report upon follong code.
The data source object is invalid.
Code is here
Cursor = Cursors.WaitCursor;
timer1.Enabled = true;
CrystalReport2 rpt = new CrystalReport2();
obj.connection();
String accept = "SELECT S.Product as Products, COALESCE(Pur_Orders.Quantity, 0) as [Products purchased], COALESCE(Sale_Orders.Quantity, 0) as [Products Sold] From Inv_stock S LEFT JOIN (SELECT Item, SUM(Quantity) AS Quantity FROM Pur_Orders Where Pur_Orders.Date='" + dateTimePicker1.Value.Date + "' GROUP BY Item) AS Pur_Orders ON S.Product = Pur_Orders.Item LEFT JOIN (SELECT Item, SUM(Quantity) AS Quantity FROM Sale_Orders Where Sale_Orders.Date='" + dateTimePicker1.Value.Date + "' GROUP BY Item) AS Sale_Orders ON S.Product = Sale_Orders.Item";
SqlCommand cmd = new SqlCommand(accept, obj.con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Inv_stock");
da.Fill(ds, "Pur_Orders");
da.Fill(ds, "Sale_Orders");
rpt.SetDataSource(da);
obj.con.Close();
Inventory inv = new Inventory();
inv.CrystalReportViewer.ReportSource = rpt;
inv.Visible = true;
What is problem?????
You are setting the datasource of the report with DataAdapter:
rpt.SetDataSource(da);
Replace it with a dataset or a datatable like this:
rpt.SetDataSource(ds); // a dataset
rpt.SetDataSource(ds.Tables["TableName"]); // a datatable
You should make a View of the Nested Query and Check it and then call that specific view when u are making a new Report as Datasourse.
If your Query is Correct but Datasourse is invalid you will not get you Desired output on the Report..
I have this code
SqlConnection conn = Database.GetConnection();
//not sure why doing this bit (bit between this comment and next
//SqlDataAdapter adapter = new SqlDataAdapter("Select * From CarType", conn);
DataSet DataSetRentals2 = new DataSet("CustomerSQLTable");
DataTable table = new DataTable("CustomerSQLTable"); //you can name it
DataTable table2 = new DataTable("CarRental");
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand("SELECT * FROM Customer", conn);
conn.Open();
///this might brake the code
///
adapter.Fill(DataSetRentals2,"CustomerSQLTable");
adapter.SelectCommand = new SqlCommand("SELECT * FROM CarRental", conn);
adapter.Fill(DataSetRentals2, "CarRental");
adapter.Fill(DataSetRentals2, "CarRental");
}
CustomerGrid.DataSource = DataSetRentals2;
CustomerGrid.DataMember = "CustomerSQLTable";
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
CarRGrid.DataMember = "CarRental";
the teacher gave me this code to link them in a relationship so that when i click on one customer number in one data grid and for it to only return corresponding records in the other.
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals2.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();.
so what i think i need to do is to name the columns in the dataset. But i have no idea how to do this. I'm sure there must be a way an I'm sure you guy's can easily tell me it. Thank you in advanced.
dataTable.Columns[0].ColumnName = "MyColumnName";
Your columns will already have names. They are supplied by the database.
I would guess that your issue is with this line. If this isn't it please describe what you're expecting to happen, vs what is actually happening so that we may assist you better.
CarRGrid.DataSource = DataSetRentals2.Tables["CarRental"];
Which should probably be
CarRGrid.DataSource = DataSetRentals2;