SQL error on join and group by - sql-server

What is wrong with the fallowing SQL statement? I'm getting the error describe below. I'm using Microsoft SQL Server 2012.
The SQL statement:
SELECT
ContentRequests.Title,ContentRequests.ChapterOrArticleTitle,
ContentRequests.Institution_Id,
Institutions.Name
FROM
[HexDatabaseDev].[dbo].[ContentRequests]
LEFT JOIN
Institutions ON Institutions.Id = ContentRequests.Institution_Id
GROUP BY
ContentRequests.Title
The error I'm getting :
Column 'HexDatabaseDev.dbo.ContentRequests.ChapterOrArticleTitle' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Rule of Group By..
In the select clause,you can ignore only the columns involving aggregates or constants,rest of the columns in select should be in Group By
So in your case.
group by
ContentRequests.ChapterOrArticleTitle,ContentRequests.ChapterOrArticleTitle
,ContentRequests.Institution_Id
, Institutions.Name

Related

Why would one specific SQL Server Database fail to convert VARCHAR to NUMERIC?

Is it possible that 2 different SQL Server databases, having the same schema and data, could process a query in a different way, and one of them throwing a " Error converting data type varchar to numeric. " error, while the other one doesn't?
For example, see this query:
SELECT count(*) FROM DEPARTMENTS dpt
inner join
EMPLOYEES emp
on dpt.subgroup_id = emp.subgroup_id
WHERE
emp.employee_id = 12856
and
dpt.department_id in
(
select cm.mapped_value from CONFIGURATIONS c
inner join
CONFIG_MAPPINGS cm on cm.configuration_id = c.id
where
c.name = 'Department that can override self-destruction protocol'
)
The inner select subquery is returning either a value that can be cast to a number, or no results at all. So what I've noticed is that:
One database running Microsoft SQL Server 2012 - 11.0.2100.60 executes the query without errors, as long as the inner statement will not return a non-numeric value
Another database running Microsoft SQL Server 2012 (SP4-GDR) (KB4057116) - 11.0.7462.6 is always throwing the "Error converting data type varchar to numeric." error, regardless of what the inner select query returns.
I've also noticed that if I change the subquery with another one that returns exactly the same, but without the inner join, the 2nd database is not throwing the error
SELECT count(*) FROM DEPARTMENTS dpt
inner join
EMPLOYEES emp
on dpt.subgroup_id = emp.subgroup_id
WHERE
emp.employee_id = 12856
and
dpt.department_id in
(
select cm.mapped_value FROM CONFIG_MAPPINGS
WHERE cm.configuration_id = 'DPT_OVERRIDE_SDP'
)
I know that I should improve the query anyway, adding a ISNUMERIC check, but just out of curiosity, my question is:
Could it be that one these databases is processing the query in a different way (perhaps different execution plan) and always exposes the error, while the other database manages to execute the query?
Execute this queries:
select cm.mapped_value FROM CONFIG_MAPPINGS
WHERE cm.configuration_id = 'DPT_OVERRIDE_SDP' AND ISNUMERIC(cm.mapped_value)<>1
and
select cm.mapped_value from CONFIGURATIONS c
inner join
CONFIG_MAPPINGS cm on cm.configuration_id = c.id
where
c.name = 'Department that can override self-destruction protocol'
AND ISNUMERIC(cm.mapped_value)<>1
to see which values are the reason of error. Then you can use "ISNUMERIC(cm.mapped_value)=1" in your internal query to ignore them.
After comparing the execution plans on both databases, I've noticed they are quite different.
If the plan was joining DEPARTMENTS and CONFIG_MAPPINGS before joining CONFIG_MAPPINGS with CONFIGURATIONS, and before the c.name = .. filter was applied, then we would be joining on dpt.department_id (numeric) = cm.mapped_value, while mapped_value would also contain non-numeric values at that point.
This is the case with the 2nd database, and this explains the conversion error

Symmetricds Initial Load with Order by SQL Server

I am trying to do an initial load of data based on order by creationtime column. My sym_trigger_router (for currencies table ) has below initial_load_select :-
initial_load_select = "1 = 1 order by t.CreationTime"
which create query as below :-
select count(*)
from "board"."dbo"."currencies" t
where 1=1
order by t.CreationTime desc;
It works with MySQL but not with SQL Server because SQL Server does not support order by with count(*).
I'm getting this error :
[head-85711c60-84d5-4527-b31f-a861aa8caa9a] - JdbcSqlTemplate - SQL caused exception: [select count(*) from "board"."dbo"."currencies" t where 1=1 order by t.CreationTime desc ]
java.sql.SQLException: Column "board.dbo.currencies.creationtime" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
As per this link
When 0 is specified for initial_load_batch_count, SymmetricDS will
execute a count(*) query on the table during the extract process
but symmetricds 3.9 has removed this column, now what is workaround to ignore count(*) query for SQL Server for initial load?
Any help?

COUNT(1) in DB2

I have query where there is COUNT(1) in select statement.
I want to know what does it return. COUNT(*) will return the number of rows but COUNT(1) I have no idea. I tried to execute one statement in DB2 but got error saying COLUMN OR EXPRESSION IN THE SELECT LIST IS NOT VALID.
Post your SQL statement.
I suspect you have something like
select customer, count(1)
from salesHistory
In which case, DB2 isn't complaining about count(1) which is perfectly valid; but it's complaining because you've got a aggregate function in the select list along with a non-aggregate column. In order to do that, you have to include a GROUP BY clause.
select customer, count(1)
from salesHistory
group by customer

What are the causes of an AS not being able to work under SQL Server?

I am running into a rather aggravating issue with the "AS" keyword in SQL server. I am doing multiple LEFT JOINs and using the AS keyword to create aliases for the result sets. I've tried to define an alias on a particular query and getting an error stating "Incorrect syntax near AS". The query will go through successfully, but SQL server is just not allowing me to define an alias.
I've researched and attempted to find some more thorough documentation on what can and cannot be done with the AS keyword. I'm also seriously considering the possibility that I've written a built-in somewhere and am just missing it.
I've extracted parts of other SQL I've written involving multiple JOINs, but I'm running into the same issue. Here is an example of the query I'm dealing with now:
SELECT
D.ProjectID [Project ID],
D.VendorID [Vendor ID],
VND.VendorName [Name],
D.Modifiedby [User Modified]
FROM
( SELECT
ProjectID,
VendorID,
Modifiedby
FROM [Project].[ProjectDocument]
) AS D
LEFT JOIN
( SELECT
VendorID,
VendorName
FROM [VendorTable].[Vendor]
) AS VND
ON D.VendorID = VND.VendorID AS V
Are there any reasons as to why the AS keyword would be rejected by SQL server?
The last statement says:
ON D.VendorID = VND.VendorID AS V
Remove the AS V from the back.

Querying aggregate columns in a SQL Server SELECT statement

I have a SQL Server query which runs just fine -- until I add a computed column to the SELECT statement. Then I get an odd SQL Server error.
Here's the SQL:
SELECT
outmail_.MessageID_,
CONVERT(VARCHAR(10),outmail_.Created_,120) AS 'Issue',
lyrReportSummaryData.mailed,
lyrReportSummaryData.successes,
COUNT(*) AS 'opens',
COUNT(DISTINCT clicktracking_.MemberID_) AS 'unique_opens',
convert(decimal(3,1),((convert(float,[unique_opens]))/[successes]) * 100) AS 'Rate'
FROM
outmail_
RIGHT JOIN
clicktracking_ ON clicktracking_.MessageID_ = outmail_.MessageID_
RIGHT JOIN
lyrReportSummaryData ON lyrReportSummaryData.id = clicktracking_.MessageID_
GROUP BY
outmail_.MessageID_, CONVERT(VARCHAR(10), outmail_.Created_,120),
lyrReportSummaryData.mailed, lyrReportSummaryData.successes
The problem is the line beginning with the convert(decimal ... When it is included, I get the following error:
Error 8120: Column 'lyrReportSummaryData.unique_opens' is invalid in
the select list because it is not contained in either an aggregate
function or the GROUP BY clause.
I'm not sure how to resolve the error since I don't know how to use it in a GROUP BY clause (and it doesn't seem that I should need to do so).
Any suggestions for how to proceed? Thanks.
I'm sure someone with better DBA skills than me can point out a more efficient way of doing this, but...
If you perform the bulk of your query as an sub-query, you can then do the calculations on the result of your sub-query:
SELECT
MessageID_,
Issue,
mailed,
successes,
opens,
unique_opens,
convert(decimal(3,1),((convert(float,[unique_opens]))/[successes]) * 100) AS 'Rate'
FROM
(SELECT
outmail_.MessageID_,
CONVERT(VARCHAR(10),outmail_.Created_,120) AS 'Issue',
lyrReportSummaryData.mailed,
lyrReportSummaryData.successes,
COUNT(*) AS 'opens',
COUNT(DISTINCT clicktracking_.MemberID_) AS 'unique_opens'
FROM outmail_
RIGHT JOIN clicktracking_ ON clicktracking_.MessageID_ = outmail_.MessageID_
RIGHT JOIN lyrReportSummaryData ON lyrReportSummaryData.id = clicktracking_.MessageID_
GROUP BY outmail_.MessageID_, CONVERT(VARCHAR(10), outmail_.Created_,120), lyrReportSummaryData.mailed, lyrReportSummaryData.successes
) subquery /* was 'g' */
Effectively what this does is runs the grouping, and then based on that, does the calculation afterwards.
Subqueries must be given an alias (in this instance 'subquery') - even if you don't use that alias name.

Resources