Link to home
Start Free TrialLog in
Avatar of erikTsomik
erikTsomikFlag for United States of America

asked on

sql query grouping

I have a query which works just fine. I wan to add 2 additional columns to calculate the records with the same ID.

The query output is attached

I need to count number of the same records AreaID and CLTID, and put them in the separate column.
Avatar of Argenti
Flag of France image


for the given query output you provided, what would be the expected output after modifying the query?
Avatar of erikTsomik


the same output .I just need 2 columns which will do the count. I know the number will be repeated multiple times, i will sort it out on the output
Avatar of Brian Crowe
Please provide your initial query and what version of SQL Server you are operating in.

To provide some sort of advice:

Turn your original query into a common table expression and use multiple references...

WITH cte (itemID, ID, ItemCLID, name, Descr, iconID, CLTname, AreaID, CLTID)
   <your query here>
SELECT itemID, ID, ItemCLID, name, Descr, iconID, CLTname, AreaID, CLTID,
   (SELECT COUNT(*) FROM cte AS cteAreaID WHERE cteAreaID.AreaID = cte.AreaID),
FROM cte
   itemID, ID, ItemCLID, name, Descr, iconID, CLTname, AreaID, CLTID,
   (select count(*) from my_table T1 where T1.AreaID = T.AreaID) as CountAreaID,
   (select count(*) from my_table T1 where T1.CLTID = T.CLTID) as CountCLTID
   my_table T
Avatar of Brian Crowe
Brian Crowe
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
both MySQL & MS SQL Server are chosen as topics, but the syntax options for your request can differ depending on which dbms you are actually using - please only select the topics that are relevant to your question.

& Providing your existing query would:
a. reveal which dbms you are using
b. enable experts to propose a precise solution quickly
c. save you time as you don't have to choose from options that can't be used
d. saves the voluntary time of experts from proposing options you cannot use

nb: if you need a "cross platform" solution for both MySQL & MS SQL Server I would suggest you state that in the question.

(Argenti's correlated subqueries would be cross platform btw, but
we don't know the full extent of the existing query and those subqueries may require more details in the where clauses
there may be options giving better performance