How to get the maxvalue of the following query [duplicate] - sql

This question already has answers here:
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Closed 8 years ago.
I have this query and i need to get the maxvalue of the CCSEQ camp, i have tried using this query but it doesn´t work, if anyone can help me i will be very grateful.
the query
select max(cc.CCSEQ), cc.ccline4, cc.ccstreetno, cccity
from ccontact cc
where customer_id = '724609' and ccbill = 'X';
EDIT
I have resolved the issue with this query
select cc.ccline4, cc.ccstreetno, cccity
from ccontact cc
where CC.customer_id = '724609' and CC.ccbill = 'X'
AND cc.CCSEQ = (SELECT MAX(C1.CCSEQ) FROM ccontact c1
WHERE CC.customer_id = C1.customer_id)
Best wishes

Don't mix plain columns with aggregates if you don't group by those plain columns:
select max(cc.CCSEQ)
from ccontact cc
where customer_id = '724609' and ccbill = 'X';

It's difficult to determine the absolute right query without knowing the schema, but my guess is that you want the Max CCSEQ and the respective ccline4, ccstreetno, and cccity for your selection. There are a few ways to do this. With a subquery it would look like:
SELECT
cc.ccseq, cc.ccline4, cc.ccstreetno, cccity
FROM
(SELECT max(cc.CCSEQ) AS maxccseq FROM ccontact WHERE customer_id = '724609' and ccbill = 'X') as ccmax
INNER JOIN ccontact cc ON
ccmax.maxccseq = cc.CCSEQ

Related

Sub-query works but would a join or other alternative be better?

I am trying to select rows from one table where the id referenced in those rows matches the unique id from another table that relates to it like so:
SELECT *
FROM booklet_tickets
WHERE bookletId = (SELECT id
FROM booklets
WHERE bookletNum = 2000
AND seasonId = 9
AND bookletTypeId = 3)
With the bookletNum/seasonId/bookletTypeId being filled in by a user form and inserted into the query.
This works and returns what I want but seems messy. Is a join better to use in this type of scenario?
If there is even a possibility for your subquery to return multiple value you should use in instead:
SELECT *
FROM booklet_tickets
WHERE bookletId in (SELECT id
FROM booklets
WHERE bookletNum = 2000
AND seasonId = 9
AND bookletTypeId = 3)
But I would prefer exists over in :
SELECT *
FROM booklet_tickets bt
WHERE EXISTS (SELECT 1
FROM booklets b
WHERE bookletNum = 2000
AND seasonId = 9
AND bookletTypeId = 3
AND b.id = bt.bookletId)
It is not possible to give a "Yes it's better" or "no it's not" answer for this type of scenario.
My personal rule of thumb if number of rows in a table is less than 1 million, I do not care optimising "SELECT WHERE IN" types of queries as SQL Server Query Optimizer is smart enough to pick an appropriate plan for the query.
In reality however you often need more values from a joined table in the final resultset so a JOIN with a filter WHERE clause might make more sense, such as:
SELECT BT.*, B.SeasonId
FROM booklet_tickes BT
INNER JOIN booklets B ON BT.bookletId = B.id
WHERE B.bookletNum = 2000
AND B.seasonId = 9
AND B.bookletTypeId = 3
To me it comes down to a question of style rather than anything else, write your code so that it'll be easier for you to understand it months later. So pick a certain style and then stick to it :)
The question however is old as the time itself :)
SQL JOIN vs IN performance?

How can I update this column with an aggregate function? [duplicate]

This question already has answers here:
SQL update query using joins
(13 answers)
Closed 2 years ago.
I calculated a sum for OREB that is unique to every pair of GameId and TeamId
using this query,
Query Image.
select DGAM.GameID, HomeTeamID, SUM(OREB) as OREB_Home
from dimGames as DGAM
join dimPerformance as DPERF on DGAM.GameID = DPERF.GAME_ID and DGAM.HomeTeamID = DPERF.TEAM_ID
group by DGAM.GameID, HomeTeamID
Using the results of this query I want to update the null column in this table
Table called dimGames.
How can I write an update statement to accomplish this?
Adapting this answer, I think you want:
with agg as (
select DGAM.GameID, HomeTeamID, SUM(OREB) as OREB_Home
from dimGames as DGAM
join dimPerformance as DPERF on DGAM.GameID = DPERF.GAME_ID and DGAM.HomeTeamID = DPERF.TEAM_ID
group by DGAM.GameID, HomeTeamID
)
UPDATE dimGames dg
SET dg.OREB_home = agg.OREB_Home
FROM agg
WHERE dg.GameId = agg.GameId and dg.HomeTeamId = agg.HomeTeamId

SQL GROUP BY function returning incorrect SUM amount

I've been working on this problem, researching what I could be doing wrong but I can't seem to find an answer or fault in the code that I've written. I'm currently extracting data from a MS SQL Server database, with a WHERE clause successfully filtering the results to what I want. I get roughly 4 rows per employee, and want to add together a value column. The moment I add the GROUP BY clause against the employee ID, and put a SUM against the value, I'm getting a number that is completely wrong. I suspect the SQL code is ignoring my WHERE clause.
Below is a small selection of data:
hr_empl_code hr_doll_paid
1 20.5
1 51.25
1 102.49
1 560
I expect that a GROUP BY and SUM clause would give me the value of 734.24. The value I'm given is 211461.12. Through troubleshooting, I added a COUNT(*) column to my query to work out how many lines it's running against, and it's giving a result of 1152, furthering reinforces my belief that it's ignoring my WHERE clause.
My SQL code is as below. Most of it has been generated by the front-end application that I'm running it from, so there is some additional code in there that I believe does assist the query.
SELECT DISTINCT
T000.hr_empl_code,
SUM(T175.hr_doll_paid)
FROM
hrtempnm T000,
qmvempms T001,
hrtmspay T166,
hrtpaytp T175,
hrtptype T177
WHERE 1 = 1
AND T000.hr_empl_code = T001.hr_empl_code
AND T001.hr_empl_code = T166.hr_empl_code
AND T001.hr_empl_code = T175.hr_empl_code
AND T001.hr_ploy_ment = T166.hr_ploy_ment
AND T001.hr_ploy_ment = T175.hr_ploy_ment
AND T175.hr_paym_code = T177.hr_paym_code
AND T166.hr_pyrl_code = 'f' AND T166.hr_paid_dati = 20180404
AND (T175.hr_paym_type = 'd' OR T175.hr_paym_type = 't')
GROUP BY T000.hr_empl_code
ORDER BY hr_empl_code
I'm really lost where it could be going wrong. I have stripped out the additional WHERE AND and brought it down to just T166.hr_empl_code = T175.hr_empl_code, but it doesn't make a different.
By no means am I any expert in SQL Server and queries, but I have decent grasp on the technology. Any help would be very appreciated!
Group by is not wrong, how you are using it is wrong.
SELECT
T000.hr_empl_code,
T.totpaid
FROM
hrtempnm T000
inner join (SELECT
hr_empl_code,
SUM(hr_doll_paid) as totPaid
FROM
hrtpaytp T175
where hr_paym_type = 'd' OR hr_paym_type = 't'
GROUP BY hr_empl_code
) T on t.hr_empl_code = T000.hr_empl_code
where exists
(select * from qmvempms T001,
hrtmspay T166,
hrtpaytp T175,
hrtptype T177
WHERE T000.hr_empl_code = T001.hr_empl_code
AND T001.hr_empl_code = T166.hr_empl_code
AND T001.hr_empl_code = T175.hr_empl_code
AND T001.hr_ploy_ment = T166.hr_ploy_ment
AND T001.hr_ploy_ment = T175.hr_ploy_ment
AND T175.hr_paym_code = T177.hr_paym_code
AND T166.hr_pyrl_code = 'f' AND T166.hr_paid_dati = 20180404
)
ORDER BY hr_empl_code
Note: It would be more clear if you have used joins instead of old style joining with where.

How to use count correctly in sql?

I have tow tables 'matches' and 'forum' I need to get match information from the matches table which has comments in the forum table so I use the following query:
SELECT distinct forum.match_static_id, matches.*
from forum
INNER JOIN matches
ON forum.match_static_id = matches.static_id
WHERE forum.comments_yes_or_no = 1
I use distinct to avoid getting the same match twice if it has more than one comment in the forum table.
The problem is I want to get the count of each match comments with the same query is it possible? I use :
SELECT distinct forum.match_static_id, count(forum.comments), matches.*
from forum
INNER JOIN matches
ON forum.match_static_id = matches.static_i
WHERE forum.comments_yes_or_no = 1
but it give me just one record (which is wrong). What is the problem ?? does I need to use group by ? and if yes where to but it in this crowded query?
Please try this:
SELECT forum.match_static_id, count(matches.id), matches.*
from forum
INNER JOIN matches
ON forum.match_static_id = matches.static_i
WHERE forum.comments_yes_or_no = 1
GROUP BY forum.id

SQL Reporting count of parameter in a column

I am working in SSRS 3.0 with a SQL table including the following fields:
ApptID BookedBy ConfirmedBy CancelledBy
I also have a parameter setup to select which users to filter by (matches data in the BookedBy, ConfirmedBy and CancelledBy columns) called #Scheduler (which is a multi vale parameter/array).
I need to get a count for booked, confirmed and scheduled for how many times any value in the Scheduler parameter shows up in that column.
Basically:
COUNT(BookedBy IN (#Scheduler)) AS BookedCount
Can anyone help me out with the syntax for doing this?
Try this
SELECT Count(BookedBy = #Scheduler) as [BookedCount],
Count(ConfirmedBy = #Scheduler) as [ConfirmedCount],
Count(CancelledBy = #Scheduler) as [CancelledCount]
FROM tablename
WHERE BookedBy = #Scheduler OR
ConfirmedBy = #Scheduler OR
CancelledBy = #Scheduler
NB - Not tested might contain typos
If your input is a list separated by commas you can convert that to a table. See a reference like this:
http://www.projectdmx.com/tsql/sqlarrays.aspx
For this use case I'd recommend one of the solutions that saves the result in a CTE (since you only need to convert your input once and this will be fastest)
Then you could use that table (called sTable with column name) like this:
SELECT Count(Bo.Name) as [BookedCount],
Count(Co.Name) as [ConfirmedCount],
Count(Ca.Name) as [CancelledCount]
FROM tablename
LEFT JOIN sTable Bo ON BookedBy = Bo.name
LEFT JOIN sTable Co ON ConfirmedBy = Co.name
LEFT JOIN sTable Ca ON CancelledBy = Ca.name
I guess this will work but it does not seem as nice as the others:
SELECT (SELECT COUNT(*) FROM table WHERE BookedBy in (#Scheduler)) AS [BookedCount],
(SELECT COUNT(*) FROM table WHERE ConfirmedBy in (#Scheduler)) as [ConfirmedCount],
(SELECT COUNT(*) FROM table WHERE CancelledBy in (#Scheduler)) as [CancelledCount]