Is Group by clause supported by this lib?
I wrote query Select SectionName, DepartmentName, SUM(SalesValue) FROM ( SELECT SectionName, Date, DepartmentName, SalesValue FROM StockDaily join Section on StockDaily.idSection=Section._id join Department on StockDaily.idDepartment = Department._id where idStore=1 and Date >=" + '"' + from + '"' + "and Date <=" + '"' + to + '"' + ")"+" Group by SectionName
It works in sqlite manager but in cod with lib not:/ Do you have any ideas?
Yes, sqlite supports GROUP BY aggregation. Here is the reference.
Related
In a node.js/electron/sqlite3 app the following query returns correctly for all states except for 'ID'.
I've dug around for an answer, but all the solutions I've found are for queries that fail completely.
The query in question:
let stmt_data = 'SELECT DOMAIN, avg(SCORE) from( \
SELECT Domains.DOMAIN, Indicators.INDICATOR, avg(MetricScores.SCORE) as SCORE \
FROM MetricScores \
INNER JOIN Counties ON MetricScores.FIPS == Counties.FIPS \
INNER JOIN MetricVariables ON MetricScores.METRIC_VAR_ID == MetricVariables.ID \
INNER JOIN MetricGroups ON MetricVariables.METRIC_GROUP_ID == MetricGroups.ID \
INNER JOIN Domains ON MetricVariables.DOMAIN_ID == Domains.ID \
INNER JOIN Indicators ON MetricVariables.INDICATOR_ID == Indicators.ID \
WHERE Counties.COUNTY_NAME == "' + comp_location['COUNTY_NAME'] + '" AND Counties.STATE_CODE == "' + comp_location['STATE_CODE'] + '" AND METRIC_GROUP == "HWBI" \
Group By Domains.DOMAIN, Indicators.INDICATOR) Group By DOMAIN';
A value of 'ID' in the query # comp_location['STATE_CODE'] results in the following error:
SQLITE_ERROR: ambiguous column name: ID
I realize it is an issue with columns that have the same name as this value. I am confused as to why changing a comparison value would break this query.
I have found a solution/work-around:
changing
WHERE Counties.COUNTY_NAME == "' + comp_location['COUNTY_NAME'] + '" AND Counties.STATE_CODE == "' + comp_location['STATE_CODE'] + '" AND METRIC_GROUP == "HWBI"
to
WHERE Counties.COUNTY_NAME == ? AND Counties.STATE_CODE == ? AND METRIC_GROUP == "HWBI"
and passing the variables to
db.all(sql, [county, state], (err, rows) => {...});
provides the expected behavior, but I am still interested in why the original sql statement fails.
I have an SQL Query for each of my 2 Gridview elements. One is getting all the transactions by branch and transaction date:
SELECT
tb_TransactionDetails.TxnID,
tb_TransactionDetails.BranchCode,
tb_TransactionDetails.TxnDate,
tb_TransactionDetails.ReferenceNo,
tb_TransactionType.TxnTypeName,
tb_CurrencyCode.CCYDesc,
tb_TransactionDetails.CCYAmount,
tb_RecordStatus.StatusDesc,
(tb_TransactionName.FirstName + ' ' + ISNULL(tb_TransactionName.MiddleName,'') + ' ' + ISNULL(tb_TransactionName.LastName,'')) as 'Client',
(tb_TransactionName.AddressLine1 + ' ' + ISNULL(tb_TransactionName.AddressLine2, '') + ' ' + ISNULL(tb_TransactionName.AddressLine3, '')) as 'Address',
tb_TransactionName.WhoAdded,
tb_TransactionName.DateAdded,
ROW_NUMBER() OVER
(ORDER BY BranchCode ) AS RowNumber
FROM (((tb_TransactionType inner join tb_TransactionDetails
on tb_TransactionType.TxnTypeCode = tb_TransactionDetails.TxnType)
INNER JOIN tb_CurrencyCode on tb_TransactionDetails.CCYCode = tb_CurrencyCode.CCYCode)
inner join tb_RecordStatus on tb_TransactionDetails.RecordStatus = tb_RecordStatus.StatusCode)
LEFT JOIN tb_TransactionName
on tb_TransactionDetails.TxnID = tb_TransactionName.TxnID
WHERE BranchCode = '1003'
and TxnDate = '12/13/2013'
and one is getting all the users in the system:
select
USR.UserName,
USR.BranchID,
(ISNULL(USR.FirstName,'') + ' ' + ISNULL((SUBSTRING(USR.MiddleName,1,1) + '.' ),'') + ' ' + ISNULL(USR.LastName,'')) as 'Name',
MBS.IsLockedOut,
USR.LastActivityDate,
MAX(STUFF(fxMerge.RoleId, 1, 2, '')) as 'Roles'
from (aspnet_Membership as MBS inner join aspnet_Users as USR
on USR.ApplicationId = USR.ApplicationId and MBS.UserId = USR.UserId)
inner join aspnet_UsersInRoles UIR
on USR.UserId = UIR.UserId
CROSS APPLY(
SELECT ', ' + RoleName
FROM aspnet_UsersInRoles UIR1
INNER JOIN aspnet_Roles RM ON UIR1.RoleId = RM.RoleID
WHERE UIR.UserId = UIR1.UserId
FOR XML PATH('')) fxMerge (RoleId)
where USR.UserName = 'JSmith'
group by USR.UserName, USR.BranchID, USR.FirstName, USR.MiddleName, USR.LastName, MBS.IsLockedOut, USR.LastActivityDate
one thing I'm confused about, is that the 1st query does not need a GROUP BY clause, while the 2nd one does. My question is, why? I've been running the 1st query hundreds of times no problem in my system, without ever having the need of a GROUP BY clause, and the Gridview displays the expected results. While on my 2nd query, It's only when I add the long GROUP BY clause that the query executes successfully on the SQL Server Management studio, then nothing shows up on my Gridview.
That's because your second query has a MAX(). If you want the highest or lowest value, or the count or any other aggregate function, you'll need to specify how to group it.
I have this select statement:
SELECT *
FROM Room
LEFT JOIN booking ON (Room.RoomId = booking.RoomId)
WHERE booking.Roomid is null
AND GETDATE() BETWEEN bookin.checkindate '" + TxtCheckIn.Text + "'
AND booking.checkoutdate '" + TxtCheckOut.Text + "'" + "
ORDER BY Room.RoomType
I want to check in the booking table if the date matches the checkin and checkout dates selected by users. If it doesn't match, the query should show all rooms in the room table (even if it is in the booking table), provided that they have different dates.
You need to determine whether any rows match the condition on the date. To do this, the following query moves the date condition into the on clause. Then it uses the window function count() to count the number of matches. If there are none, then all rows are returned. Otherwise, only matches are returned.
select t.*
from (SELECT *, count(booking.RoomId) over () as numMatches
FROM Room LEFT JOIN
booking
ON Room.RoomId = booking.RoomId and
GETDATE() BETWEEN booking.checkindate '" + TxtCheckIn.Text + "' and
booking.checkoutdate '" + TxtCheckOut.Text + "'" + "
) t
where numMatches > 0 and RoomId is not null or numMatches = 0
ORDER BY Room.RoomType
Is it possible to add carriage returns and line feeds into the CommandText of a TableAdapter so the results of the query displays them in an ASP.Net GridView?
Here is part of a query in the TableAdapter I made using the DataSet designer:
SELECT AsthmaTreatment,
BookFee, ClinicWhenIll, DateOfBirth, Forename, GPA, Grade, HealthProblems, ID,
IllnessDetails, InjuryDetails, InsuranceCompany, InsurancePolicyNumber,
LanguagesSpoken, MedicinesTaken, ParentID,
(SELECT MotherName + ' *** ' + FatherName + '***' + CHAR(13) + CHAR(10) +
AddressLine1 + CHAR(13) + CHAR(10) +
AddressLine2 + CHAR(13) + CHAR(10) +
City + ', ' + State + ' ' + Zip AS Expr1
FROM Parents WHERE (ID = Students.ParentID)) AS ParentName,
PrimaryDoctor, PrimaryDoctorPhone, PrimaryPhone, SecondaryPhone,
SurgeryDetails, Surname, TuitionFee, email
FROM Students
WHERE (Forename LIKE '%' + #SearchValue + '%') OR
(Surname LIKE '%' + #SearchValue + '%') OR
(#SearchValue = 'ALL')
Using the query described above, the GridView data is shown without the carriage returns and line feeds separating the lines of data.
We are looking to show the data like this in the GridView:
Ismail Eva *** Emad-ud-deen ***
123 Test St
Apt. 100
New York, NY 10021
Mustafa Eva *** Emad-ud-deen ***
333 First Ave.
Unit 3-B
Lowell, MA 01852
the problem is the character's themselves. (browsers, html) do not translate char 10 & 13. Browsers do undertand HTML markup, so you can use <p>, <div>, or <br> tags to format the text.
I would do this in the HTML markup though, not the sql statement.
I have this SQL Statement:
de.SqlStatement = "SELECT A.Name, A.Catagory , COUNT(Patient_ID) AS PNO FROM PatientApplyToAssociation P INNER JOIN Association A on A.Association_ID = P.Association_ID WHERE A.Catagory='" & "health" & " '" & "' GROUP BY A.Name '"
with this Exception:
System.Data.SqlClient.SqlException was unhandled by user code
Class=16
ErrorCode=-2146232060
LineNumber=1
Message=Column
'Association.Name' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
I had this exception when I added the where clause, It seems that the compiler cant see the Group By Section , because of the quotation ending before it, I tried to write it like this:
de.SqlStatement = "SELECT A.Name, A.Catagory , COUNT(Patient_ID) AS PNO FROM PatientApplyToAssociation P INNER JOIN Association A on A.Association_ID = P.Association_ID WHERE A.Catagory='" & "health" & "' GROUP BY A.Name '" & " '"
But it was an Incorrect syntax near ' '.
Any ideas?
I'm pretty sure you don't want the ' around the GROUP BY clause:
SELECT A.Name, A.Catagory
, COUNT(Patient_ID) AS PNO
FROM PatientApplyToAssociation P
INNER JOIN Association A
ON A.Association_ID = P.Association_ID
WHERE A.Catagory='" & "health" & " '" & " GROUP BY A.Name
In order to use the statement in your original question, you will need to revise it to be:
de.SqlStatement = "SELECT A.Name, A.Catagory, COUNT(1) AS PNO FROM PatientApplyToAssociation P INNER JOIN Association A on A.Association_ID = P.Association_ID WHERE A.Catagory='health' GROUP BY A.Name, A.Catagory"
There are 3 changes in this statement:
1) The extraneous string joins in the where and group by have been removed.
2) Group by A.Catagory has been added so that you will not receive another error similar to error in the question for this field.
3) COUNT(Patient_ID) has been changed to COUNT(1) as a possibly better practice. If the field you are counting contains nulls, it will not be included in the count. If this is the desired behavior, then your previous code was correct; otherwise you should use the revision.