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
Related
The database stores the currency exchange rate on a given day. Each day, one currency exchange value is collected and stored in the database as:
ID (int, AI)
VALUE
DATE
1
2.5
20.01.2021
2
2.7
21.01.2021
3
2.6
22.01.2021
If I would like to calculate the average exchange rate from the last 10 days, should I first sort the data by date and only retrieve the last 10 records when downloading the data, or is it enough to download the last 10 records from the database without sorting?
You can simply do in SQL Server database
SELECT TOP 10 AVG(VALUE) AS AverageRate
FROM YourTable
ORDER BY Id DESC
Concept should be same in other relational databases.
Tables (and table expressions such as views and CTEs) in SQL represent unordered sets. To get data in a particular order, you must specify an ORDER BY clause.
In fairly generic SQL you can do
SELECT AVG(VALUE) AS AverageRate
FROM (
SELECT VALUE
FROM YourTable AS t
ORDER BY Id DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY
) AS t
In some RDBMSs, instead of OFFSET FETCH, you use either LIMIT or TOP to achieve the same effect. You still need ORDER BY.
You can do it in both ways.
If you're using SQL with Dapper or ADO.NET, then you can write a query.
It should be sorted if you need the last 10 values
SELECT TOP 10 AVG(your value) AS average
FROM YourCurrencyExchangeTable
ORDER BY DATE DESC
If you're using EntityFrameWorkCore, you can write
var avg = db.yourDbContext
.Where(c => c.Date >= tenDaysAgoDate)
.Average(c => c.yourValue)
I hope my answer helps :)
Basically you have to sort first ( on date) and then get the last 10 values, so you're on the right track.
I am using Microsoft SQL Database Management Studio and it will not allow me to use the strftime() function to run a query. I have to create a table by months with new users and unsubscribers for each month.
This is what I had essentially which creates the error:
SELECT strftime('%m', createddate) AS 'Month', COUNT(createddate) AS 'Subscribers',
COUNT(dateunsubscribed) AS 'UNsubscribers'
FROM subscriber
GROUP BY 1
ORDER BY 1;
how else could I run this query without strftime() or how can I get strftime() to work?
strftime is a mysql function, and isn't available in Microsoft's sql-server.
For this simple usecase (extracting a month from a date), you could user month:
SELECT MONTH(createddate) AS [Month],
COUNT(createddate) AS [Subscribers],
COUNT(dateunsubscribed) AS [UNsubscribers]
FROM subscriber
GROUP BY 1
ORDER BY 1;
EDIT:
To address the question in the comment, the group by clause doesn't take an ordinal like the order by clause does. You'll need to specify the expression you want to group by:
SELECT MONTH(createddate) AS [Month],
COUNT(createddate) AS [Subscribers],
COUNT(dateunsubscribed) AS [UNsubscribers]
FROM subscriber
GROUP BY 1
ORDER BY MONTH(createddate);
I have some very odd behaviour from a MySQL query in my C# application which is pulling rows from a Table called project_info. It should retrieve all the Rows which Equal the Customer's Name, and the project start date is BETWEEN the DATE range in the query. The current query I am using works but the date range appears to behave very oddly...
For example if I have a Row in my Table which contains a project for Customer 'WHSmith' and they have a project with a start date of '30/07/2018' when I search with a date range BETWEEN 18/06/2018 AND 01/08/2018 the query returns no results, but if I repeat the query using a date range BETWEEN 18/06/2018 AND 02/08/2018 the Row is returned???
The query I currently have is:
SELECT * FROM project_info WHERE cust_name = "WHSmith" AND proj_date BETWEEN 2018-06-18 AND 2018-08-01;
The date is stored as a DATE field in the table so no Time is included in the query or the value... The cust_name and dates are held in variables within my application but I have checked these are correct and seem OK.
Does anyone have any idea why the BETWEEN query is behaving so oddly? or maybe suggest a better way to look for Row's in a DATE range... many thanks.
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.
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)