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);
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 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
I am rewriting an SProc in c#. the problem is that in SProc there is a query like this:
select top 1 *
from ClientDebt
where ClinetID = 11234
order by Balance desc
For example :I have a client with 3 debts, all of them have same balance. the debt ids are : 1,2,3
c# equivalent of that query is :
debts.OrderByDescending(d => d.Balance)
.FirstOrDefault()
debts represent clients 3 debts
the interesting part is that sql return debt with Id 2 but c# code returns Id 1.
The Id 1 make sense for me But in order to keep code functionality the same I need to change the c# code to return middle one.
I do not sure what is the logic behind sql top 1 where several rows match the query.
The query will select one debt and update the database. I would like the linq to return the same result with sql
Thanks
debts.OrderByDescending(d => d.Balance).ThenByDescending(d => d.Id)
.FirstOrDefault()
You can start SQL Profiler, execute stored procedure, review result, and then catch query which application send through linq, and again review result.
Also, you can easily view execution plan of you procedure, and try it to optimize, but with linq query, you cannot easily do this.
AFAIK, IN SQL if you select rows without ORDER BY, it orders the resultset based on the primary key.
With Order BY CLAUSE [field], implicitly next order is [primarykey].
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)
I using linqer want this sql to liqn query but i have problem
select * from Project where Id in (select Top 3 ForeignId from ActivityLog
group by ForeignId order by count(*) desc)
Problem :SQL cannot be converted to LINQ: Field [Id in (select Top 3 ForeignId from ActivityLog group by ForeignId order by count(*) desc)] not found in the current Data Context.
I just had a similar issue with linqer. I found the solution was removing the ; after the SQL query and trying again.
It could be an issue with your context.
See Linqer – a nice tool for SQL to LINQ transition for instructions on setting up the context.
Also, make sure the *.dbml and *.designer.cs files are up to date and define the Project table to contain an Id column and the ActivityLog table to contain a ForeignId column.
This could be a bug with the version of linqer you are using. I am using 4.0.3 and was able to run the same query (adjusted to use my tables) without issue.