SQL query for searching the dates - c#

I have written a SQL query which search the employee ATTENDANCE Table for the persons who are absent. But how can I show the dates I mean the date of the absent period? It works fine except the date. I want to show what's the day of that absent period? I am unable to show the date.
Sample:
BadgeNumber - EmployeeName - Absent Date
10042 - Mr. Erik - 2014-07-01
Code:
SELECT SMEmployee.BadgeNumber,SMEmployee.EmployeeFullName,SMDepartment.DepartmentName
FROM SMEmployee
LEFT OUTER JOIN SMDepartment
ON SMDepartment.DepartmentID=SMEmployee.DepartmentID
WHERE EmployeeID NOT IN (
SELECT empCheckInOut.USERID
FROM empCheckInOut
WHERE convert(date,CHECKTIME)='2014-07-01')

Normally to check for the lack of existence of a record (as you are doing here for attendence, checking the employee did not check in / out on a day) it is more efficient to use a LEFT OUTER JOIN and the check for NULL in one of the fields in the WHERE clause (ie, a LEFT JOIN where no row found).
However this also won't give you the date.
I presume that you want to check a selection of dates, and this need to pull through the date they were absent.
As such maybe use a series of unioned simple queries to get the dates, CROSS JOIN that to your employee table and LEFT JOIN it to the empCheckInOut table. This way you can put out the date.
SELECT SMEmployee.BadgeNumber,SMEmployee.EmployeeFullName,SMDepartment.DepartmentName, subDate.aDate
FROM SMEmployee
CROSS JOIN (SELECT '2014-07-01' AS aDate UNION SELECT '2014-06-30') subDate
LEFT OUTER JOIN SMDepartment
ON SMDepartment.DepartmentID=SMEmployee.DepartmentID
LEFT OUTER JOIN empCheckInOut
ON SMEmployee.EmployeeID = empCheckInOut.USERID
AND convert(date,CHECKTIME) = subDate.aDate
WHERE empCheckInOut.USERID IS NULL

It seems that you capture the days employee is present in 'empCheckInOut' table.
You need to construct temp table with all the dates lets say of 1 month and then minus the dates that are captured in 'empCheckInOut' table.
e.g. #temp will have 06-01-2014, 06-02-2014, 06-03-2014, ... (all 30 days of Jun)
CheckInOut will have 06-01-2014, 06-03-2014,... (emp is absent on 2nd Jun, so total 29 days of Jun captured here)
Then, subtract one from the other and you will get dates when employee is absent.

Related

Asp.net(C#), how to do sql statement that order by a counted field

I’m working on a project which is an online shop,
I want to show in a page the most sold items,
So my sql is
Select (*), Count(Product_ID) as n from Order_Details order by n desc.
But it doesn’t work. Can someone help?
You need to aggregate the data first, this can be done using the GROUP BY clause:
SELECT (*), COUNT(DISTINCT Product_ID)
FROM table
GROUP BY Product_ID
ORDER BY COUNT(DISTINCT Product_ID) DESC
The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.
SELECT (*), Max(DISTINCT Product_ID)
FROM table
GROUP BY Product_ID
ORDER BY Max(DISTINCT Product_ID) DESC
the most sold item you use max

SQL Server CE count group by

I want to create a SQL query that will do the counting for me instead of in the razor code, I want to calculate the amount of distinct dates in my database.
I found that SQL Server CE does not support count(distinct column_name) and instead using group by would be the solution, but for some reason I could not make it work, what am I doing wrong?
SELECT COUNT(date) as date
FROM Test
GROUP BY date
This simply counted every date in my database and not the distinct ones when writing it out like the following
var totalcount = 0;
foreach (var c in db.Query(query))
{
var ttotalcount = c.date;
totalcount += ttotalcount;
}
<a>#totalcount<a>
Updated
Your query is asking for the counts of each distinct date. If you want to know how many of those you have you need to sum them up. You can do this be nesting your query with a SUM query. Then use an additional column defulted to "1", to allow to sum up the number of rows (which should be your distinct dates). Also date can be a reserved word. You might want to try and avoid using that as a column name.
SELECT SUM(New_Row) as dateSUM from (
SELECT COUNT(date) as dateCount, 1 as New_Row FROM Test GROUP BY date
) a
Maybe:
SELECT COUNT(date) as [date]
FROM Test
GROUP BY date
Date is a reserved word, need to add []
You are confusing SQL with the three usages of date. I am assuming that the original field is named date. I am also assuming that each record has the date field populated.
SELECT COUNT(*) as numDates FROM Test GROUP BY date

How do you sum a column of a database to display total ratings in ASP.NET?

I'm trying to make a ratings system. I'm using visual studio. The database has 2 tables, one table for all the music tracks, and another table containing the ratings, and is hooked up with an FK.
Here's my tables and columns
http://i.gyazo.com/fc5d042749c8c04fb2b9aa2b64831b0a.png
This is my current attempt and it's giving me an error
SELECT DISTINCT Track.TrackId, SUM(Ratings.rating) AS average, Track.Name, Ratings.trackid
FROM Track
INNER JOIN Ratings
ON Track.TrackId = Ratings.trackid
Msg 8120, Level 16, State 1, Line 1
Column 'Track.TrackId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Every time you are using either a sum, avr, min or max, etc. functions you have to use Group by that is the law..
What you need to do first is SUM the ratings by track and then joining those later with your track table, something like this:
SELECT T.TrackId, SUM(R.rating) AS average, T.Name
FROM Track T
INNER JOIN
(SELECT TrackId, SUM(Ratings.rating) AS average
FROM Ratings Group By TrackId ) R
ON T.TrackId = r.TrackId
If you want to use aggregation functions, then you generally want a group by. Without the group by, the query will return only one row.
SELECT t.TrackId, SUM(r.rating) AS average, t.Name
FROM Track t INNER JOIN
Ratings r
ON t.TrackId = r.trackid
GROUP BY t.TrackId, t.name;
In addition, I made the following changes:
Removed distinct from the select. This is almost never needed for an aggregation query.
Added table aliases that are abbreviations of the table names, to make the query more readable.
Removed Ratings.TrackId from the select statement. It is redundant, because it is the same as Track.TrackId.
Added a group by statement.
Don't use distinct. It doesn't do the same thing as Group By.
In SQL-think, what you're trying to do is group all the rows by Trackid, and average the rating in each group which you do like this:
SELECT Track.TrackId, AVG(1.0000 * Ratings.rating) AS average
FROM Track
JOIN Ratings ON Track.TrackId = Ratings.trackid
Group By Track.TrackId
But, you're also trying to pick up the Name at the same time. Doing that at that same time as a group by isn't as straightforward in SQL as you might wish. A 'correct' way is something like:
SELECT
Track.TrackId,
Average,
Name
FROM Track
INNER JOIN (
SELECT TrackId, AVG(1.0000 * Ratings.rating) AS average
FROM Ratings
Group By TrackId
) R
ON Track.TrackId = R.trackid

C# and SQL Server 2005

I have 4 tables from which I am fetching records. The first three tables required inner join with the common rows but with 4th table I need left outer join because I have to preserve the already fetched rows from first three tables.
Now, problem is that I want left join with fourth table but it should only pick the records having date = current date. I am passing current date from C# while calling my stored procedure. But the thing is SQL Server is giving null records.
Here is the query::
alter procedure
(#currentdate varchar(50))
select distinct
table1.name, table2.class,table3.stream
from
table1
inner join
table 2 on table1.id = table2.id
inner join
table3 on table3.id=table2.id
left outer join
table 4 on table 4.id = table3.id and table4.date = #currentdate
I used and with left outer join because I want records in that way where as using where clause filters the whole result and just give me one record.
Then also I used casting with both the dates in stored procedure but no positive response.
From C# I'm using
var date = datetime.now.toshortdate();
CallStoredProcedure(date)
Please help me regarding this ASAP. Thank you
First of all - you should use the appropriate type for your dates - that is DATETIME - do not cast dates into strings and back if you can avoid it! (and you can definitely avoid it here)
Secondly: the DATETIME in SQL Server as well as the DateTime in .NET both have dates and time information, e.g. 2013-06-23 14:57:34 so if you're doing an equality comparison in your JOIN condition, only those rows that exactly match your date and time will be selected. So you need strip off the time portion, if you want to use just dates for comparison.
So try this code here:
ALTER PROCEDURE dbo.YourProcedureNameHere (#currentdate DATETIME)
SELECT DISTINCT
table1.name, table2.class, table3.stream
FROM
dbo.table1
INNER JOIN
dbo.table2 ON table1.id = table2.id
INNER JOIN
dbo.table3 ON table3.id = table2.id
LEFT OUTER JOIN
table 4 ON table 4.id = table3.id
AND DATEADD(DAY, DATEDIFF(DAY, 0, table4.date), 0) =
DATEADD(DAY, DATEDIFF(DAY, 0, #currentdate), 0)
This strips off the time portion of your table4.date as well as #currentdate and then the comparison will be done on just the date (no time involved). Once you've updated to SQL Server 2008 or newer, I would recommend to use the DATE datatype which is designed exactly for this - storing just the date (no time). Unfortunately, that's not yet available in SQL Server 2005.
Also, from C# - use this line to call your stored procedure:
var date = Datetime.Today;
CallStoredProcedure(date);

SQL Server CE GROUP BY clause

I have to use GROUP BY statement to pull data from SQL Server CE.
Now I'm getting
In aggregate and grouping expressions, the SELECT clause can contain
only aggregates and grouping expressions. [ Select clause = ,Date ]
but I really want to get date.
Query is as follows
SELECT Date
FROM Installments
GROUP BY ID
HAVING Sr = max(Sr)
What am I doing wrong? Please explain
When you use group by, you group by some field, and apply an aggregate function.
So, in the select, you shoud that field (the grouped result) and then the result of the function used.
Maybe you want something like
SELECT Id, Max(date) FROM Installments GROUP BY ID
It will depends on what you want.
Read about Group by here
If you are grouping by ID, then each group could potentially have multiple different dates, so you can't select Date. You could, for example,
select Max(Date) FROM Installments GROUP BY ID
As it says, you need to include the columns you're returning in the group by clause.
SELECT Date FROM Installments GROUP BY ID, Date
I suspect what you may be trying to do is this
SELECT Date
FROM Installments
WHERE sr = (Select MAX(sr) from Installments)

Categories

Resources