SQL how to select data in terms of weeks - sql

Is it in any way possible to select data from the database in spans of weeks?
I use cshtml (not MVC) and webmatrix if that makes any difference.
var dbQueryAllVariants = "SELECT * FROM Test WHERE exercise = " + exercise + " AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
So right now I'm using this, I put in a start date (ex. 2016-11-01) and end date (ex. 2016-11-30) (yyyy-mm-dd cuz north europe). This displays all the data in the database between those dates but since all rows in the database only have a day as date, the result to be viewed would be in day form, I'd like if it can do weeks, in this case, from first to last november as an example would be aprox 4 weeks, is this possible? Also, the data in the database is int values so I would like to be able to add those up to display a total of the week that gets displayed if that makes sense.
For example.
column 1 column 2 column 3
5 . . . . 6 . . 2016-11-13
8 . . . . 10 . . 2016-11-15
6 . . . . 3 . . 2016-11-17
So as of right now it would display 3 days with a sum of 11 for day 1, 18 for day 2 and 9 for day 3, but while displayed in terms of weeks it would be 11+18+9=38, as for an example. This might not even be possible to begin with but I'd like to know how to do this if possible!
If this isn't a possible solution, is there a way to like select all the data in day form, put it in a array or whatever, and from there send it grouped as a weekly total based on the weeks of the year (ex. november contains week 44-48) something like that? What I'm trying to say is that if the end result is what I want, it doesn't matter how its done.
#{
//Calls for my website layout.
Layout = "~/_SiteLayout.cshtml";
//Browser title of the specific page.
Page.Title = "TEST";
//Opens database.
var db = Database.Open("SmallBakery");
//Variables.
var exercise = Request.Form["Exercise"];
var fromDate = Request.Form["fromDate"];
var toDate = Request.Form["toDate"];
var exerVariName = "";
var exerVariNameS = "";
var exerVariNameB = "";
var exerVariNameD = "";
//Defaults to show data between these
//dates if user dont choose any dates.
var noStartDate = "1970-01/01";
var noEndDate = "2099-12/31";
//If user does not choose eiter/any start/end date
//this will end up showing all results possible.
if (fromDate == "") {
fromDate = noStartDate;
}
if (toDate == "") {
toDate = noEndDate;
}
//Takes exerVariName from different dropdowns
//depending on which exercise is selected due to
//the fact that only one dropdown is visible at any time.
if (exercise == "1") {
exerVariName = Request.Form["exerVariNameS"];
} else if (exercise == "2") {
exerVariName = Request.Form["exerVariNameB"];
} else {
exerVariName = Request.Form["exerVariNameD"];
}
//Gets exercise variants to the dropdown menu.
var getSVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 1 ORDER BY exerVariName";
var getBVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 2 ORDER BY exerVariName";
var getDVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 3 ORDER BY exerVariName";
var getData = "SELECT * FROM Test";
//Gets the date.
var getDate = "SELECT date FROM Test";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<!-- Form for posting. -->
<form method="post" action="">
<!-- Radio buttons to select which data to show. -->
<div>
<label>Squat</label>
<input type="radio" name="Exercise" id="hej1" value="1" />
</div>
<div>
<label>Benchpress</label>
<input type="radio" name="Exercise" id="hej2" value="2" />
</div>
<div>
<label>Deadlift</label>
<input type="radio" name="Exercise" id="hej3" value="3" />
</div>
<div>
<!-- Dropdown menu with squat-variant-names. -->
<select id="exerVariNameS" name="exerVariNameS">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getSVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
<!-- Dropdown menu with bench-variant-names. -->
<select id="exerVariNameB" name="exerVariNameB">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getBVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
<!-- Dropdown menu with deadlift-variant-names. -->
<select id="exerVariNameD" name="exerVariNameD">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getDVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
</div>
<div>
<!-- Date calendar. -->
<input placeholder="From date..." type="text" class="datepicker" name="fromDate" value="#fromDate">
</div>
<div>
<!-- Date calendar. -->
<input placeholder="To date..." type="text" class="datepicker" name="toDate" value="#toDate">
</div>
<!-- The submit button. -->
<input type="submit" value="Show" class="submit" />
</form>
<!-- Displays database value on submit click based on choosen radiobutton from form-post above. -->
#if (IsPost) {
//When I select ALL in the dropdown it runs
//this line because there is no filter for 'exerVariName'.
// var dbQueryAllVariants = "SELECT * FROM Test WHERE exercise = " + exercise + " AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
//When I select a specific exercise variation.
var dbQuerySingleVariant = "SELECT * FROM Test WHERE exercise = " + exercise + " AND exerVariName = '" + exerVariName + "' AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
//This is what the problem is....
var dbQueryAllVariants = "SELECT DATEPART(week, date) AS weekNumber, sum(kg)+sum(sett) AS grandTotalPerWeek FROM Test WHERE Exercise = " + exercise + " AND DATEPART(week, date) BETWEEN DATEPART(week, " + fromDate + ") AND DATEPART(week, " + toDate + ") GROUP BY DATEPART(week, date)";
var dbQuery = "";
//If dropdown = select all, it does, else, it show the one I pick.
if (exerVariName == "all") {
dbQuery = dbQueryAllVariants;
} else {
dbQuery = dbQuerySingleVariant;
}
//Foreach to write out all the data from db.
var sumTotalWeight = 0;
foreach (var get in db.Query(dbQuery)) {
<a>Weight: </a>
<a>#get.Kg kg</a>
<a> Sets: </a>
<a>#get.Sett</a>
<a> Reps: </a>
<a>#get.Rep</a>
<a> Total reps: </a>#(get.Sett * get.Rep)
<a> #get.date</a>
var totalWeight = #get.Kg * #get.Sett * #get.Rep;
sumTotalWeight += totalWeight;
<a> #totalWeight</a>
<br>
}
#sumTotalWeight
}
</body>

From your comments one may conclude you are using the MSSQL Server Compact Edition.
If that's correct then you could use the DATEPART function to extract the week of the year for each date, and then group by week and sum all results for each.
Something like this:
SELECT
sum(column1)+sum(column2) AS grandTotalPerWeek
FROM Test
WHERE Exercise = {Exercise}
AND DATEPART(week, date) = {weekNumber}
Where {Exercise} and {weekNumber} are the variables to be substituted.
Or like this, if you need to request multiple weeks at once:
SELECT
DATEPART(week, date) AS weekNumber,
sum(column1)+sum(column2) AS grandTotalPerWeek
FROM Test
WHERE Exercise = {Exercise}
AND DATEPART(week, date) IN ({listOfWeekNumbers})
GROUP BY DATEPART(week, date)
Where {Exercise} and {listOfWeekNumbers} are the variables to be substituted.
In either case, when we talk about week numbers we talk about integer values. 1 means the first week of the year, 2 the second week, ...
Example: Get the values for January
SELECT
DATEPART(week, date) AS weekNumber,
sum(kg)+sum(sett) AS grandTotalPerWeek
FROM Test
WHERE Exercise = 1
AND DATEPART(week, date) IN (1,2,3,4)
GROUP BY DATEPART(week, date)
So, to use this SQL you need to translate dates into week numbers. If you only have dateFrom and dateTo then you can try something like this:
SELECT
DATEPART(week, date) AS weekNumber,
sum(kg)+sum(sett) AS grandTotalPerWeek
FROM Test
WHERE Exercise = 1
AND DATEPART(week, date) BETWEEN DATEPART(week, {dateFrom}) AND DATEPART(week, {dateTo})
GROUP BY DATEPART(week, date)
DATEPART documentation on MSDN.

Related

Show date from database on Picker materialize

I have the following code, when I click on the Picker I want to see the date 01/01/2018 selected in the calendar.
I need the calendar to select the date that contains the value of the imput.
$var_date = '01/01/2018';
<input type="text" name="date" name="date" class="datepicker" value="<?php echo $var_date; ?>">
<label for="first_name">Date</label>
This can be done with the help of instance.setDate(new Date()).
<input type="text" class="datepicker">
<script>
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelector('.datepicker');
var instance = M.Datepicker.init(elems);
// instance.open(); This will open your datepicker on its own when page is loaded completely
instance.setDate(new Date(2018, 2, 8));
});
</script>
Note- new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
The argument monthIndex is 0-based. This means that January = 0 and December = 11
MDN - Date
Materialize - Pickers

SQL statement check for concatenated value and return statement if not found

I am trying to search a two column table with a CustomerID and a ServID. The primary key is the combination of both. I want the query to search if the combination is there. If it is return something I can use in c# to cancel the input or if it is not found have it insert the record. This is as far as I have made it after hours of searching.
IF (SELECT * FROM Cus_Ser WHERE customerID=inputnumber AND ServID=inputnumber) IS NULL
PRINT 'Already Exists'
ELSE
INSERT INTO Cus_Ser(CustomerID,ServID) VALUES(inputnumber, inputnumber)
Here is the code
#using WebMatrix.Data
#{
var CustomerID = Request.QueryString["CustomerID"];
var ServID = 0;
var db = Database.Open("Azure");
var selectedData = db.Query("SELECT * FROM Customer INNER JOIN Cus_Ser ON Customer.customerID=Cus_Ser.customerID INNER JOIN Service ON Cus_Ser.ServID=Service.ServID WHERE customer.CustomerID =" + CustomerID);
var grid = new WebGrid(source: selectedData);
var selectedData2 = db.Query("SELECT * FROM Service");
var grid2 = new WebGrid(source: selectedData2);
if (IsPost)
{ if (int.TryParse(Request.Form["ServID"], out int numbertest))
{
ServID = Int32.Parse(Request.Form["ServID"]);
var dbCommandSearch = "SELECT * FROM Cus_Ser WHERE customerID=" + CustomerID + " AND ServID=" + ServID;
//search = db.QuerySingle(dbCommandSearch);
//if ((CustomerID, "ServID") != search
db = Database.Open("Azure");
var insertCommand = "INSERT INTO cus_ser (customerID,ServID)VALUES(" + CustomerID + ", " + ServID + ")";
db.Execute(insertCommand);
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
//else
//{
//Validation.AddFormError("Entered Value is Not a Service Numberr");
//}
else
{
Validation.AddFormError("Entered Value is NOT a Service Number");
}
} }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add Service</title>
<style>
.validation-summary-errors {
border: 2px dashed red;
color: red;
font-weight: bold;
margin: 12px;
}
</style>
</head>
<body>
<form method="post">
<fieldset>
<legend>Input Service To Add</legend>
<p>
<label for="ServID">Service ID:</label>
<input type="text" name="ServID" value="#ServID" />
</p>
<input type="hidden" name="CustomerID" value="#CustomerID" />
<p><input type="submit" name="buttonSubmit" value="Submit Changes" /></p>
</fieldset>
</form>
<p>Return to customer listing</p>
Multiple Inline SQL Statements
Your sample code seems to be very close. The QuerySingle method will return null if no matches are found. Thus you can check for a null value before issuing the insert statement, with something like:
ServID = Int32.Parse(Request.Form["ServID"]);
var dbCommandSearch = "SELECT * FROM Cus_Ser WHERE customerID=" + CustomerID + " AND ServID=" + ServID;
search = db.QuerySingle(dbCommandSearch);
if (search == null) { // record does not already exist
var insertCommand = "INSERT INTO cus_ser (customerID,ServID)VALUES(" + CustomerID + ", " + ServID + ")";
db.Execute(insertCommand);
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
else
{
Validation.AddFormError("Entered Value is Not a Service Numberr");
}
Single SQL Statement
You can combine this all into one big SQL statement, something like:
var sql = #"IF EXISTS (SELECT 1 FROM Cus_Ser WHERE customerID=#0 AND ServID=#1)
SELECT 0 as [Inserted];
ELSE
BEGIN
INSERT INTO Cus_Ser(CustomerID,ServID) VALUES(#0, #1)
SELECT 1 as [Inserted];
END";
You can execute this as a parameterized query, which is much safer* than the code you have:
var response = db.QuerySingle(sql, CustomerID, ServID); // passing the input value as a parameter
if (response.Inserted == 1) {
// WebMatrix might convert to a bool, in which you would want `response.Inserted == true` instead
Response.Redirect("~/ViewService?CustomerID=" + CustomerID);
}
else
{
Validation.AddFormError("Entered Value is Not a Service Numberr");
}
As I am not deeply familiar with WebMatrix, I am not 100% sure about this code. Hopefully it sets you in the right direction.
A word of warning: your original code is vulnerable to something called a SQL injection attack. Most programmers start out making that mistake; I know that I did. In summary: that inputnumber parameter could have a SQL statement in it instead of a number. If someone crafts that SQL Statement just right, then they could cause a lot of damage. For an entry-level programming assignment it is not something to worry about in detail. But as you progress in coding, you will need to learn how to use parameterized queries in order to guard against SQL injection. A few useful references:
SQL Injection
Introduction to Working with a Database in ASP.NET Web Pages (Razor) Sites

ASP.NET Razor split record and increase by one

in my code I'm trying to display in a text box the record that follows the last one of my database. For example, if my last record is A560 I want to display A561. To achieve this I know I have to split the record and then manipulate it, but I haven't had any luck. Here is what the database looks like:
Point_ID Project No. Project Manager Comments
A558 1304 Oscar Duran Found destroyed
A559 1304 Oscar Duran Helicopter access
A560 1356 Julio Bravo Airport parking lot
This is my code so far:
#{
Layout = "~/_Layout.cshtml";
var db = Database.Open("ControlPoints");
var SelectCommand = "SELECT * FROM( SELECT TOP 5 * FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC )AS BaseData Order BY Point_ID ASC";
var SearchTerm = "";
if(!Request.QueryString["SearchCP"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE Point_ID = #0";
SearchTerm = Request.QueryString["SearchCP"];
}
if(!Request.QueryString["SearchProject"].IsEmpty() ){
SelectCommand = "SELECT * FROM AllControlMergedND WHERE [Project Used on] LIKE #0";
SearchTerm = "%" + Request["SearchProject"] + "%";
}
var SelectData = db.Query(SelectCommand, SearchTerm);
var grid = new WebGrid(source: SelectData, rowsPerPage: 10);
}
#{
Validation.RequireField("Point_ID", " Required");
Validation.RequireField("ProjectNo", " Required");
Validation.RequireField("ProjectManager", " Required");
var Point_ID = "";
var ProjectNo = "";
var ProjectManager = "";
if(IsPost && Validation.IsValid() ){
Point_ID = Request.Form["Point_ID"];
ProjectNo = Request.Form["ProjectNo"];
ProjectManager = Request.Form["ProjectManager"];
db = Database.Open("ControlPoints");
var InsertCommand = "INSERT INTO AllControlMergedND ([Point_ID], [Project No.], [Project Manager]) VALUES(#0, #1, #2)";
db.Execute(InsertCommand, Point_ID, ProjectNo, ProjectManager);
}
var SelectLastCP = "SELECT TOP 1 Point_ID FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC";
var SelectData2 = db.QuerySingle(SelectLastCP);
var SuggestedPoint_ID = SelectData2.Point_ID;
}
<h2>Airborne Imaging Control Points Database</h2><br/><br/>
<form method="get">
<fieldset>
<legend>Search Criteria</legend>
<div>
<p><label for="SearchCP">Control Point ID:</label>
<input type="text" name="SearchCP" value="#Request.QueryString["SearchCP"]" />
<input type="submit" value="Search"/></p>
</div>
<div>
<p><label for="SearchProject">Project:</label>
<input type="text" name="SearchProject" value="#Request.QueryString["SearchProject"]" />
<input type="Submit" value="Search" /></p>
</div>
</fieldset>
</form>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Point_ID"),
grid.Column("Project No."),
grid.Column("Project Used on"),
grid.Column("WGS84 Lat"),
grid.Column("WGS84 Long"),
grid.Column("Ellips_Ht"),
grid.Column("Project Manager"),
grid.Column("Comments")
)
)
<br/><br/>
</div>
<form method="post">
<fieldset>
<legend>Create Control Point(s)</legend>
<p><label for="Point_ID">Point ID:</label>
<input type="text" name="Point_ID" value="#SuggestedPoint_ID" />
#Html.ValidationMessage("Point_ID")</p>
<p><label for="ProjectNo">Project No:</label>
<input type="text" name="ProjectNo" value="#Request.Form["ProjectNo"]" />
#Html.ValidationMessage("ProjectNo")</p>
<p><label for="ProjectManager">Project Manager:</label>
<input type="text" name="ProjectManager" value="#Request.Form["ProjectManager"]" />
#Html.ValidationMessage("ProjectManager")</p>
<p><input type="submit" name="ButtonConfirm" value="Confirm" /></p>
</fieldset>
</form>
As you can see, all I am able to do is to display the last record of my database in the text box, which in this case would be A560. The variable 'SuggestedPoint_ID' is holding that record. I have tried converting the data type, but had no success. Any help would be greatly appreciated.
Update:
What I need is to do the following. Split A560 in two parts 'A' and '560'. Then increment '560' by one to obtain '561' and finally attach 'A' again to '561' in order to obtain the next increment 'A561'.
If you are trying to convert "A560" to int for example then it won't work because you don't have a valid number. A needs to be removed.
var SuggestedPoint_ID = SelectData2.Point_ID.Replace("A", "");
This is not my recommended way to do it as A could be anything such as AA or B or ZZZZ. My point is that you need to describe what you need to get a better solution to your problem.
UPDATE
var source = "A560";
var lhs = source.Substring(0, 1);
var tmp = source.Replace(lhs, "");
int rhs;
if(int.TryParse(tmp, out rhs))
{
rhs++;
}
var result = string.Format("{0}{1}", lhs, rhs);

Bootstrap DatePicker Splitting Date

I'm in the process of updating an old booking systems views and I am presently stuck on a solution for updating the calendar widget. As the site is responsive I have opted for the bootstrap datepicker supplied by eternicode https://github.com/eternicode/bootstrap-datepicker.
OK here the issue. I have an old Datepicker that splits the checkin & checkout dates into 3 parts and then formats the date for PHP (n = Month no leading zero)) (j = Day no leading zero) & (Y = Year 4 digit numeric).
// Initiate Params
$checkInDate = mktime(0,0,0,date("n"),date("j") + 1,date("Y"));
$checkOutDate = mktime(0,0,0,date("n"),date("j") + 3,date("Y"));
//CheckInDate
if (!isset($daysI)){
$daysI = date("j",$checkInDate);
}
if (!isset($monthsI)){
$monthsI = date("n",$checkInDate);
}
if (!isset($yearI)){
$yearI = date("Y",$checkInDate);
}
//CheckOutDate
if (!isset($daysS)){
$daysS = date("j",$checkOutDate);
}
if (!isset($monthsS)){
$monthsS = date("n",$checkOutDate);
}
if (!isset($yearS)){
$yearS = date("Y",$checkOutDate);
}
The input boxes markup is as below.
<input type='text' id='fulldate' name='fulldate'>
<label>Enter Day of Arrival (in the format DD) </label>
<input type="text" name="daysI" id="daysI" size="6" maxlength="6" />
<label>Enter Month of Arrival (in the format MM) </label>
<input type="text" name="monthsI" id="monthsI" size="6" maxlength="6" />
<label>Enter Year of Arrival (in the format YYYY) </label>
<input type="text" name="yearI" id="yearI" size="6" maxlength="6" />
Here's where I'm having the problem. The following function works with jQuery UI:
$('#fulldate').datepicker({
showAnim: 'fadeIn',
dateFormat: 'd/m/yy',
onSelect: function(dateText, inst) {
var pieces = dateText.split('/');
$('#daysI').val(pieces[0]);
$('#daysI').val(pieces[1]);
$('#daysI').val(pieces[2]);
}
});
However I cannot get a similar solution to work with the bootstrap-datepicker which I am using as a replacement for jQuery UI ie:
$('#fulldate').datepicker({
format: "d/m/yyyy",
todayBtn: "linked",
todayHighlight: true
onSelect: function(dateText, inst) {
var pieces = dateText.split('/');
$('#daysI').val(pieces[0]);
$('#monthsI').val(pieces[1]);
$('#yearI').val(pieces[2]);
}
});
Thank in advance for any solution..
The documentation gives an example of how to capture the date changed event: bootstrap-datepicker Docs - Change Date Event
Something like this should be in the right direction (untested):
$('#fulldate').datepicker()
.on('changeDate', function(ev){
var newDate = new Date(ev.date);
$('#daysI').val(newDate.getDate());
$('#monthsI').val(newDate.getMonth());
$('#yearI').val(newDate.getFullYear());
});

Html5 type date - need full date value in database

it is my html code
<div class="required" id="join_form">
<label for="DOB">DateOfBirth:</label>
<input type="date" name="date" id="date" required pattern="(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d" aria-required="true" aria-describedby="age-format" max="2004-12-31" min="1940-12-31" />
<span id="age-format" class="help" align="center">Format: mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy</span>
</div>
javascript to validate this type=date in other browsers
var mydate = document.getElementById('date'),
mydateError = document.getElementById('age-format');
mydate.addEventListener('input', function() {
if (!mydate.value.match(/\d{4}-\d{1,2}-\d{1,2}/)) {
mydateError.innerHTML = 'Please specify a valid date in the form 1940-2004 ';
mydateError.style.display = 'inline-block;font-size:6pt;text-align:center;';
} else {
var value = new Date(date.value),
min = new Date(date.min),
max = new Date(date.max);
if (value < min || value > max) {
mydateError.innerHTML = 'Date has to be between ' + min.toDateString() + ' and ' + max.toDateString();
mydateError.style.display = 'inline-block';
} else {
mydateError.style.display = 'none';
}
}
});
php validation and insert for date
$DOB=mysql_real_escape_string($_POST['date']);
$sql="INSERT INTO register(DOB) VALUES("$DOB");
i want to get whole date of birth like mm/dd/year but in my database i am only getting year like 1970 or 1987 like that....i cant figure out where i got wrong
PHP mysql insert date format
This Link did help me I used this to validate and insert type="date" in database
$timestamp = strtotime($DOB);
$date = date('d-m-y', $timestamp);
$sql="INSERT INTO register(DOB) VALUES(FROM_UNIXTIME($timestamp))";
and my other Mistake was to set DOB as int in database
Data type required in a mysql for a date containing day-month-year
it should be DATE or DATETYPE
#Tonywilk Thankx :D