Why doesn't this GROUP BY query work? - sql

I'm querying my Access table with this query:
SELECT (VIN&' '&Make&' '&Model&' '&CarYear&' '&ExColor&' '&InColor&' ')as CarDescript
FROM TestTable
WHERE (WorkOrderNumber='$workorder')
GROUP BY AssignedEmp;
But a similar type of query works just fine in this SQL Fiddle
Even if I replace the long (VIN&' '&....) with VIN it still doesn't work.
EDIT: Schema of the table is
WorkOrderNumber - Priority - JobStage - WorkItem - AssignedEmp - DueDate - VIN - Make - ... - InColor

In general use + instead of & for SQL. (Access will allow this however).
In a group by you need to pick which one in the group to use (if you are using mysql like your example it just picks a random one, see this fiddle) so to fix this in the general case for your example:
SELECT (max(VIN) + ' ' + max(Make) + ' ' + max(Model) + ' ' + max(CarYear) + ' ' + max(ExColor) + ' ' + max(InColor) + ' ')
as CarDescript
FROM TestTable
WHERE WorkOrderNumber='$workorder'
GROUP BY AssignedEmp;

Related

How can I check the maximum value from a set of tables in SQL Server (if possible)?

We have a set of databases (80 in total). Every single one has a table called tblProfessions. The tables are not standardized. For example:
EDIT: all the databases are on the same server.
The DB1.dbo.tblProfessions is like:
intProfessionCode
strProfessionDescription
1
lawyer
2
dentist
...
...
30
doctor
And the DB72.dbo.tblProfessions is as follows:
intProfessionCode
strProfessionDescription
1
designer
2
butcher
...
...
80
chef
Suppose I ran a script from DBO1 to DBO72, and I found that the biggest table has 80 entries (in this case the DBO72 is the biggest one).
By my limited knowledge, all I know is to run the below script database by database, and write it down in a spreadsheet manually:
SELECT MAX(intProfessionCode) FROM [DB].dbo.tblProfessions;
Is there a script to run and loop through all the tblProfessions and get the one with the most entries? All I want is the biggest number found.
Thanks in advance.
You should be able to do something like this:
WITH dat
AS
(
SELECT 'db1' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB1.dbo.tblProfessions
UNION ALL
...
UNION ALL
SELECT 'db72' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB72.dbo.tblProfessions
)
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall
For situations like this, I usually query the catalog to write the above script rather than typing it out:
WITH
dat AS
(
SELECT STRING_AGG('SELECT ''' + QUOTENAME(s.name) + ''' AS db,
MAX(intProfessionCode) AS max_intProfessionCode
FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME('dbo') + '.' + QUOTENAME('tblProfessions') + '
UNION ALL',' ') AS s
FROM sys.databases s
WHERE s.name LIKE 'DB%' --EDIT APPROPRIATELY
)
SELECT 'WITH dat
AS
(' + SUBSTRING(s,1,LEN(s) - LEN(' UNION ALL')) + ')
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall' AS scrpt
FROM dat;
Make sure the above is only returning data for the appropriate databases by editing the WHERE clause in the CTE, then copy the output, paste elsewhere and run it to get your results.

SQL Server - debugging SQL WHERE clause

I am new to SQL Server and I am unable to debug the Procedures.
The firewall ports aren't open for Debugging.
I am working on someone else's code and didn't understand this where clause. I didnt even think it was possible
WHERE SS_CC.FirstName + SS_CC.LastName + CONVERT(varchar(15),SS_CC.CustomerID) + RF_AS.EventType + SS_CC.AddressLine1 + SS_CC.AddressLine2 + SS_CC.City + SS_CC.[State] + SS_CC.ZipCode +
This where clause is missing something at it's right. It could be something like this:
WHERE (SS_CC.FirstName + SS_CC.LastName + CONVERT(varchar(15),SS_CC.CustomerID) + RF_AS.EventType + SS_CC.AddressLine1 + SS_CC.AddressLine2 + SS_CC.City + SS_CC.[State] + SS_CC.ZipCode
-- added part
)='something'

SQL Date Query using parameters - Delphi

I have an SQL Query (MS Access), and I want to add the Date() function into a parameter, however I get the error: [ODBC Microsoft Access Driver]Data type mismatch in criteria expression.
Here is the code:
Qry.SQL.Text := 'SELECT Bookings.Date, Bookings.WeekDay, Bookings.Shift, Bookings.Start, Bookings.Finish,'
+ ' Bookings.DateFinish, Wards.WardName'
+ ' FROM Bookings'
+ ' INNER JOIN Wards ON Bookings.WardNo = Wards.WardNo'
+ ' WHERE (Bookings.NurseNo=:nurseID) AND (Bookings.Date BETWEEN :dateA AND :dateB)'
+ ' ORDER BY Bookings.Date ASC;';
Qry.Params.ParamByName('dateA').Value := 'Date()';
Qry.Params.ParamByName('dateB').Value := 'Date()+6';
I've also tried Qry.Params.ParamByName('dateA').AsString := 'Date()'; but no luck with that, is there a correct way to do this, or would it actually have to be in the query and not parameterised? The reason I want to do it like this, is I will have multiple different queries based on which button is pressed, but the only thing changing is those parameterised dates.
A parameter can't be a function, it has to be a value. You are assigning strings as those values, and those strings do not represent valid dates. That is why you are getting a mismatch error.
You can use Delphi Date() function, and pass the returned TDate as a parameter value:
Qry.Params.ParamByName('dateA').Value := Date();
Qry.Params.ParamByName('dateB').Value := Date()+6;
Or, you can use Access's Date() function in the SQL itself:
Qry.SQL.Text := 'SELECT Bookings.Date, Bookings.WeekDay, Bookings.Shift, Bookings.Start, Bookings.Finish,'
+ ' Bookings.DateFinish, Wards.WardName'
+ ' FROM Bookings'
+ ' INNER JOIN Wards ON Bookings.WardNo = Wards.WardNo'
+ ' WHERE (Bookings.NurseNo=:nurseID) AND (Bookings.Date BETWEEN Date() AND Date() + 6)'
+ ' ORDER BY Bookings.Date ASC;';

Add Increment to create a path on SQL to be used for a CrystalReport

I am trying to come up with a the correct path for my Crystal report to pick the correct .pdf files. Here is what I have on SQL:
CASE
WHEN pd.pdCode like 'CUST%'
THEN 'Y:\300 ORDER PROCESSING\Majid Ahmadi\' + CAST(ord.ordPONumber as nvarchar(25)) + '_Custom' + '.pdf' --Added 2018-05-23 by MA
ELSE Null
END AS imageFilePath
And results:
Y:\300 ORDER PROCESSING\Majid Ahmadi\53244_Custom.pdf
Problem is I have multiple files that I want to pick. Like:
enter image description here
(picture in the link)
Any suggestion to modify my path?
Could use change the THEN to
THEN 'Y:\300 ORDER PROCESSING\Majid Ahmadi\' + CAST(ord.ordPONumber as nvarchar(25)) + '_' + pd.pdCode + '.pdf'

Getting various errors using dynamic SQL

SET #SQLSTATEMENT = 'INSERT INTO #MAX_STORAGE
SELECT MAX(A.[ROW])
FROM
(SELECT *
FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE
[FIPST_ENT] = ' + #FIPST_ENT + '
AND [FIPCNTY_ENT] = ' + #FIPCNTY_ENT + '
AND [SIC_ENT] = ' + #SIC2_ENT + '
AND [FMSZ_ENT] = ' + #FMSZENT_ENT + '
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST <= ' + #MAXIMUM_FMSZEST+'] > 0) A'
EXEC(#SQLSTATEMENT)
I was running the dynamic SQL query above as part of a stored procedure I had written and got the following error:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'A'.
I then changed my query so that it looked like this (eliminated the alias A):
SET #SQLSTATEMENT =
'INSERT INTO #MAX_STORAGE
SELECT
MAX([ROW])
FROM
(SELECT *
FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE [FIPST_ENT] = ' + #FIPST_ENT + '
AND [FIPCNTY_ENT] = ' + #FIPCNTY_ENT + '
AND [SIC_ENT] = ' + #SIC2_ENT + '
AND [FMSZ_ENT] = ' + #FMSZENT_ENT + '
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST <= ' + #MAXIMUM_FMSZEST + '] > 0)'
EXEC(#SQLSTATEMENT)
But I still ran into an error (this time different):
Msg 102, level 15, state 1, line 9
Incorrect syntax near ')'
I declared the following variables earlier in the procedure with their respective data types/lengths seen next to them:
#FIPST_ENT CHAR(2)
#FIPCNTY_ENT CHAR(3)
#SIC2_ENT CHAR(2)
#FMSZENT_ENT CHAR(1)
#MAXIMUM_FMSZENT CHAR(1)
#SQLSTATEMENT VARCHAR(MAX)
Before this dynamic SQL statement was reached in the stored procedure, the temporary table #MAX_STORAGE was already created and contains only one column of datatype int.
Am I missing something I'm doing wrong? Any help would be greatly appreciated.
Thanks.
At bare minimum, you need to enclose string fields in escaped-single-quotes within the Dynamic SQL. The adaptation I show below is based on this comment on the Question:
FIPST_ENT is numeric in nature (i.e. 01-50) but cast as a character. Likewise with the other FIPCNTY_ENT and SIC2_ENT. FMSZENT is cast as a character but is sometimes numeric (i.e. 1-9) and other times non-numeric (i.e. A-C).
So it seems that only FMSZENT needs the escaped-single-quotes.
Also, using a derived query requires an alias. So whatever the initial problem was, you then introduced a new parse error by removing the alias ;-).
SET #SQLSTATEMENT =
'INSERT INTO #MAX_STORAGE
SELECT MAX(tmp.[ROW]) FROM
(SELECT * FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE [FIPST_ENT] = '+#FIPST_ENT+'
AND [FIPCNTY_ENT] = '+#FIPCNTY_ENT+'
AND [SIC_ENT] = '+#SIC2_ENT+'
AND [FMSZ_ENT] = '''+#FMSZENT_ENT+'''
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST<='+#MAXIMUM_FMSZEST+'] > 0) tmp;'
Now, when it comes to debugging Dynamic SQL, the first step should be looking at what SQL you actually constructed, as it might not be what you think it should be:
PRINT #SQLSTATEMENT;