SQL Syntax - Group By And Having Count
Jul 23, 2005
Does anyone have any recommendations on how to solve the following?
I would like to have a query that selects ALL columns from a database,
however only records that have a count of a certain column which is
greater than 1 when the results are grouped by a few columns. I know
the following query doesnt work (because it contains items in the
SELECT that arent in the GROUP BY), but its the jist of what I need to
do.
select a,b,c,d,e,f,g,h
from table1
group by a,b,c,d
having count(e) > 1
Can anyone help me out with this?
View 3 Replies
ADVERTISEMENT
May 1, 2014
select top 15 count(*) as cnt, state from table
group by state
order by cnt desc
[code[...
Can the above three queries be combined into one and still be fast, if so how?What i am trying to go is an item count, by group, similar to ones Inbox in Outlook.
View 9 Replies
View Related
Feb 6, 2008
HiI am new to SQL and am having a problem. I need to fix my query to do the following...2) get a total of the number of rows returned.
DECLARE @StartDate varchar(12)DECLARE @EndDate varchar(12)DECLARE @Region varchar(20)
SET @StartDate = '01/01/2002'SET @EndDate = '12/31/2008'SET @Region = 'Central'
SELECTA.createdon,A.casetypecodename,A.subjectidname,A.title,A.accountid,A.customerid,A.customeridname,B.new_Region,B.new_RegionName
FROM dbo.FilteredIncident AINNER JOIN dbo.FilteredAccount B ON A.customerid = B.accountid
WHERE (A.createdon >=@StartDate AND A.createdon <= @EndDate)AND (B.new_RegionName = @Region)AND (A.casetypecode = 2)
View 1 Replies
View Related
Jan 29, 2007
I'm new to MSSQL 2005 and want to get a summary of a log table. I want to count all the rows for each date based on a DATETIME field called 'post_date' that holds the date and time of each record's creation.
this is the best I can come up with:
Code:
SELECT
DISTINCT(LEFT(post_date,11)) AS post_date, COUNT(DISTINCT(LEFT(post_date,11))) AS total_posts
FROM log_directory_contacts
GROUP BY post_date
The results show each date but the count column ('total_posts') returns '1' for every row even when I know their are more than 1 record on that date.
What am I doing wrong? Thanks!
View 9 Replies
View Related
Jul 18, 2007
Hoping someone does this 50 times a day and will know the answer.I need to build a query that groups and summarizes my data. Let's say table like this:int IDint clientType (keyed to a table with two columns [int a_ID, varchar a_clientType)]int requestType (keyed to a table with two columns [int b_ID, varchar b_requestType)]The result of the query should spit out by Client type, and with a count of how many rows of each Request Type:Client Type A [Request Type 1, # rows with Request Type 1] [Request Type 2, # rows with Request Type 2]Client Type B [Request Type 1, # rows with Request Type 1] [Request Type 2, # rows with Request Type 2]I'm still reading up on grouping and sum (though sum seems to need a field to total numbers - I need a count of row of Request Type X/Y/ZAny tips would be appreciatedThanks in advanceDave
View 14 Replies
View Related
Feb 13, 2006
IN the following query i have to get the sum of 3 columnsfrom the case statement(Builders ,Associates ,Affiliates ) in the last column.I tried sum(Productid) but it is multiplying the count by 22,23,24 respectively.
I know i have been posting this again just to get the attention of the gurus.I have come
very close to my results but this is the last hurdle i have to get thru.
Thanks for your help
select
isnull(replace(Ltrim(Rtrim(P.Firstname)),',',''),' ') Firstname
, isnull(replace(Ltrim(Rtrim(P.Lastname)),',',''),'' ) Lastname
, RecordType = isnull(replace(Ltrim(Rtrim(S.Product)),',',''),'')
, case ProductID
WHEN 22 then count(S.Product)
WHEN 23 then 0
WHEN 24 then 0
END AS Builders
, case ProductID
WHEN 23 then count(S.Product)
WHEN 22 then 0
WHEN 24 then 0
END AS Associates
, case ProductID
WHEN 24 then count(S.Product)
WHEN 23 then 0
WHEN 22 then 0
END AS Affiliates
, Total = sum (????)
FROM vwpersons p with (nolock)
join vwSubscriptions S with (nolock)
on S.RecipientID = P.ID
where (
p.firstname in (select Ltrim(Rtrim(H.name)) from externaldata.dbo.Hispanicnames H)
or
P.Lastname in (select Ltrim(Rtrim(H.name)) from externaldata.dbo.Hispanicnames H)
)
andS.ProductID in (22,23,24)
AND S.StatusID in(1,2,3,11,12)
and ((len(p.firstname)>2 or len(p.Lastname)>2))
and ((len(p.Lastname)>2 or len(p.firstname)>2))
group by P.Lastname, S.Product,S.ProductID,S.ProductID,P.Firstname
having count(P.LastName)>=1
order by 2
View 2 Replies
View Related
Mar 19, 2004
I need your help:
I want to get the total number of expired messages of two tables.
But if gives me this error:
Line 17: Syntax error near '@Count'
What did I do wrong? Am I not allowed to add two Integers??
CREATE PROCEDURE Portal_GetExpired
(
@Count int OUTPUT
)
AS
SELECT Count(*) as x
FROM Portal_Announcements
WHERE ExpireDate < GetDate()
SELECT Count(*) as y
FROM Portal_Events
WHERE ExpireDate < GetDate()
@Count=x+y
GO
View 3 Replies
View Related
Jul 20, 2005
Field Names: NOs Code Code1a UniqueID61 10 888 1062 10 888 1163 10 888 12Logic: If Count(code >1) & Count (Code1a >1)Update the (Nos) to EQUAL the same Value.ALL the Nos for the above examble should be the same value forall three records whether it's 61 for all three records of anyof the other two numbers, it doesn't matter as long as the equal the same value.How can this be done via sql?
View 5 Replies
View Related
Jan 12, 2007
Here are my 2 colums of my table;
ID LastContact
1a 4/12/2003
2d 5/12/2004
1a 9/12/2006
3c 6/12/2005
...and so on
I need to clean up this table so that I have one unique ID, with the latest 'Last Contact' date....so for this example, after the delete query I would only have '1a' with the '9/12/2006' LastContact colum..and the other two rows would be unaffected, since they didnt have a duplicate id..so after the delete query, my table would look like this;
ID LastContact
2d 5/12/2004
1a 9/12/2006
3c 6/12/2005
How would I write such a query...some sort of grouping ?
View 3 Replies
View Related
Feb 16, 2007
Hello,
I have the following code:
, COUNT(DISTINCT order_no_ocr) QTYW
from Parser_ocr
Inner Join Parser_ojb on order_no_ocr = order_no_ojb
Inner JOIN RGV_Codes on substring (compl_cde_ojb, 1, 3) = CODE
Inner JOIN csg.hist_sbb_Base on hse_key_ocr = hse_key_sbb
where substring (compl_cde_ojb, 16, 3) = CODE
and ir_tech_ojb between 950 and 999
and compl_dte_ojb BETWEEN '&low' AND '&high'
and prin_ocr = 8600
GROUP BY ir_tech_ojb, substring (compl_cde_ojb, 16, 3),compl_dte_ojb,DES, res_name_sbb, ADDR1_HSE,
job_typ_ojb, job_class_ojb, order_no_ocr, ls_chg_op_id_ocr, CommissionAUT)
group by rollup(TECHN, RESCODE,(COMPLET, DESCRIPTION, NAME, ADDRESS, JOB, TYP, NUMB, OPR))
order by 1, 2,3, 5;
And I get the following error message:
Incorrect syntax near the keyword 'group'.
What am I doing wrong here?
Thanks,
Kurt
View 5 Replies
View Related
Sep 21, 2004
I'm stuck. This is in C#.
I am making the following query:
string query = INSERT INTO region_info(prefix, region, last_update) VALUES ('" + RegionInfo.Prefix + "', '" + region + "', ???TIMESTAMP???);
and then executing
query = query.Replace("???TIMESTAMP???", "'" + DateTime.Now.ToString("yyyyMMdd") + "'");
Thus, an example query is:
INSERT INTO region_info(prefix, region, last_update) VALUES ('907209', 'Alaska-Juneau', '20040921');
When I execute this query through my program(uses ADO.net), I get a "COUNT field incorrect or syntax error" exception, but if I run this same query through the query analyzer, it works fine.
Any ideas on what'z going wrong?
Thanks
View 5 Replies
View Related
Dec 21, 2007
I want to know how to merge the following data. I am using 4 queries below. I was hoping to do it with 1 query. Table1Dist Fund VAE AOVAW AOMD CourtMD JudgeCAC AOCAC CourtVAE JudgeVAE JudgeI want to join the following 3 queries:DcountAll DcountAOSelect Dist, Count(Dist)as Count from Table1 GROUP BY Table1.Dist Select Dist, Count(Dist) as Count from Table1 Where Dist='AO' GROUP BY Table1.DistDcountCourtSelect Dist, Count(Dist) as Count from Table1 Where Dist='Court' GROUP BY Table1.DistSELECT DCountAll.Dist, DCountAll.Count, DcountAO.Count AS AO, DcountCourt.CountFROM DcountCourt RIGHT JOIN (DcountAO RIGHT JOIN DCountAll ON DcountAO.Dist = DCountAll.Dist) ON DcountCourt.Dist = DCountAll.Dist;
View 2 Replies
View Related
May 30, 2008
hi everyone, I have a table: Help
A B C05/01/2008 100 1 05/01/2008 100 205/01/2008 100 205/01/2008 200 1 05/01/2008 200 2
SELECT A, COUNT(DISTINCT C) FROM help GROUP BY A
Result:1> 05/01/2008 2I need:1> 05/01/2008 4Thanks !!!
View 4 Replies
View Related
Nov 3, 1998
TO all SQL Gurus,
The following statement returns let say 4 records -
SELECT title, price FROM table GROUP BY title
what is the correct syntax for the statement to return the count of 4 ?
if I put ->
SELECT count (*) FROM table GROUP BY title
it'll return 1.
Thanks,
Frank
View 4 Replies
View Related
May 23, 2008
Hi everybody I have this sql code
SELECT i.infid, i.infname, i.infcalled, p.pubinfid, p.pubpub, p.publang, p.pubcount, p.pubid, n.cdpldesc
FROM info AS i INNER JOIN
pubssubscribe AS p ON i.infid = p.pubinfid INNER JOIN
newpubs AS n ON p.pubid = n.pubid
WHERE (i.infcond IS NULL)AND (p.pubid BETWEEN 30 AND 33) AND (p.pubcount > 1) AND (NOT (p.publang = '.'))
there are many records where infid appears more than once because people could subscribe in different in different publicatons.
ex.
infid pubid
1 30
1 32
1 33
2 30
etc... I want to count the infid appearing once and group it with infid
thanks
View 7 Replies
View Related
Mar 25, 2004
SELECT emp_id,COUNT(*)
FROM emp
GROUP BY empId
THe above query returns the values
empid COUNT
1 4
2 4
3 5
BUT i want sum of the count (13) in the same query. How to achieve this.
Thanks.
View 4 Replies
View Related
May 29, 2008
hi everyone,
I have a table: Help
A B C
05/01/2008 100 1
05/01/2008 100 2
05/01/2008 100 2
05/02/2008 200 1
05/02/2008 200 2
SELECT a, COUNT(c) FROM Help GROUP BY a
Result:
1> 05/01/2008 3
2> 05/02/2008 2
But I need grouping columns B and C so that the result was
1> 05/01/2008 2
2> 05/02/2008 2
Is it possible? How can I do?
Thanks.
View 5 Replies
View Related
Jul 29, 2013
I want to join two tables and count the rows on the second table as something is grouped by the first. To be more clear. I have vendors and open tracking numbers for orders they have shipped. I want to list the vendor information and to group by the vendor. However I also want to count how many open orders that vendor has - which is on a different table. I have this so far:
SELECT `companyName`
, `emailAddress`
, `ccAddress`
, `dailyMessages`
, (SELECT count(*) FROM `tracking` WHERE `pkgStatus`!='4') AS 'openTracking'
FROM `vendor`
LEFT OUTER JOIN `tracking`
ON `vendor`.`id` = `tracking`.`vendorID`
WHERE (SELECT count(*) FROM `tracking` WHERE `pkgStatus`!='4') > 0
GROUP BY `vendor`.`id`
The problem is that this code results in this table. Where openTracking is always equal to the total count, not distinct to that vendor's ID
View 3 Replies
View Related
Apr 5, 2006
Hello
I'm putting together a football database and want to show how many games a player played in a season.
SELECT COUNT (PlayerFixture.FixtureID) FROM PlayerFixture WHERE PlayerFixture.PlayerID = '::PlayerID::' GROUP BY Season
However if a player doesn't play any games in a particular season the COUNT function ignores it and just returns values in seasons he has played. Is there any way i can get the COUNT function to return a "0" or "-" if a player didn't play any games that season?
Cheers
View 10 Replies
View Related
Mar 13, 2007
hi,
this sounds simple, but ive to idea how ..
1. how to count all records we found when there's group by?
SELECT ItemID, CustomLotNo, Ownership
FROM tblItemDetail
GROUP BY ItemID, CustomLotNo, Ownership
ORDER BY ItemID
2. how to print rows number for each record? like the Expr1 column
Expr1 ItemID CustomLotNo Ownership
1 A A01 INT1
2 C GPB01 JAB2MY
~~~Focus on problem, not solution~~~
View 12 Replies
View Related
Apr 24, 2008
I am doing employee shift report. I am showing totals for the shift, day and store. Store is the main group, day is the sub group under store group and shift is the sub group under the day group. I want to calculate number of shift group records (Number of shifts) and use it in the store level group calculation.
How to do it?
Thanks,
Muniappan Kandasamy
View 1 Replies
View Related
May 23, 2007
Can this be used to prevent the repetition of records displayed in a page?
Code Snippet
SELECT T_ProgramGuests, GuestName
FROM T_ProgramGuests
GROUP BY ProgramID, GuestName
HAVING (COUNT(*) > 1)
I'm trying to prevent names being repeated. I only want the name to show once followed by the next name and so on. But only once.
View 1 Replies
View Related
Jan 4, 2008
I would like to select data from a database using 'Select * " based on a value in a row (same column)being unique.
By that I mean that that data must not repeat again. Idealy I would like to set the number my self so rather then unique I could say
select the rows from the database only if the uniquevalue does not repeat more then x number of times.
eg
Value A
Value B
Value C
Value B
Value B
Value C
So if I wanted to set the uniquness to 1 then only row with Value A would be collected.
If I set the uniquenss to =<2 then I would get data from rows with value A and C so
3 rows returned.
I have this so far
SELECT *
FROM SingleS.mdb
GROUP BY Uniquevalue
HAVING count(*) = 1
View 7 Replies
View Related
May 30, 2008
Hi everyone,
I have a table: Help
A B C
05/01/2008 100 1
05/01/2008 100 2
05/01/2008 100 2
05/01/2008 200 1
05/01/2008 200 2
SELECT A, COUNT(DISTINCT C) FROM help GROUP BY A
Result:
1> 05/01/2008 2
I need:
1> 05/01/2008 4
Thanks !!!
View 12 Replies
View Related
Oct 25, 2007
Probably has been solved a million times, but here it is anyway:
Say I have a table with follwoing rows:
Site Appointment Maintenance Date
NY 13 10-25-2007
CA 14 10-29-2007
NY 18 10-25-2007
NJ NULL 10-26-2007
I need to perform a simple count showing the total (Maintenance Dates) for the next 2 days. Additionally, if a site is listed, but it doesn't have any (Maintenance Dates) for the next 2 days, it must be part of the report with the total as zero.
I can do
SELECT Site, COUNT(*)
FROM dbo.MyTable
GROUP BY Site
-- for brevity, assume GETDATE() is set to 12:00 AM, today
WHERE [Maintenance Date] >= GETDATE() AND [Maintenance Date] < DATEADD(dd, 2, GETDATE())
but this only lists NJ and NY, because they both have counts over the next days. How do I get CA in the list?
Thanks.
View 6 Replies
View Related
Oct 23, 2007
Hi,
I use group by myItem, that displays rows for each value of myItem.
I want at the end of each group for each specific myItem, I want an extra row to tell me the count of the rows for that group.
How do i do that please. Here s what I need, for example for this set of rows:
myItem colum2 colum3
711056 22662 Finances / -2291 -2479916
711056 22663 Finances / -2380 -2576255
711056 43428 Cda) -323 -349635
711056 43428 . -B-(Cda) -44 -47628
711057 44348 . -B-(Cda) -355 -384273
711057 47033 . -B-(Cda) -1278 -1383384
I need 2 extra rows, one at the end of the items 711056 telling me there are 4 rows for the item 711056 and one row at the very end telling me there are: 2 rows for the item: 711057
Thanks a lot.
View 6 Replies
View Related
Dec 7, 2007
Just out of curiosity, why would the query below error out with a syntax error near keyword group? The inside query runs fine. By the way, I know that this can be simplified by changing the projection in the inside query and moving the group by into it, but I'd like to understand why this version does not work.
Thanks!
Code Block
select paceid, count(*) as paceidcount
from
(SELECT T_MemberRoster.PaceID, T_MemberRoster.IntakeDate, T_MemberRoster.LastFullDemog, T_PACE_Demographics.CreateDate
FROM T_MemberRoster INNER JOIN
T_PACE_Demographics ON T_MemberRoster.PaceID = T_PACE_Demographics.PACE_ID AND
T_MemberRoster.DescCharEffDate = T_PACE_Demographics.DescCharEffDate
WHERE T_MemberRoster.LastFullDemog BETWEEN CONVERT(DATETIME, '2007-10-01 00:00:00', 102) AND CONVERT(DATETIME, '2007-10-31 00:00:00', 102)
)
group by paceid
order by count(*) desc
View 3 Replies
View Related
Nov 19, 2006
Hi all,
I have a problem with my query which is suppose to select count posts group by the date, the query works but doesnt return the count as i want, i think the problem that the datetime column contains also Time in hours which ofcourse isnt same in all rows in same day, so i dont know what to do, Here's my Query:
SELECT PostID, Date, COUNT(Date) AS 'TotalPosts' FROM Posts GROUP BY PostID, Date
Thank you for help
View 2 Replies
View Related
May 21, 2008
I have the following SQL Statement:
SELECT CONVERT(char(10), FixtureDate, 101) AS Date, COUNT(*) AS 'NumberOfRecords'FROM tblFixturesGROUP BY CONVERT(char(10), FixtureDate, 101)
I want to add a new column called "need results".
This column needs to be count if a certain cell is NULL.
Count If HomeScore IS NULL
as well as grouping by date and counting the number of records. So the third column needs to count the number of records where homescore IS NULL
View 1 Replies
View Related
Dec 24, 2003
Hi, I am trying to get the first row of what might be a group of any size of rows within an id that may contain a specific field. For eg
Row A = NoteID 1, FK_JobID 1, UnRead
Row B = NoteID 2, FK_JobID 1, UnRead
Row C = NoteID 3, FK_JobID 1, UnRead
I need the sql to return to just one Job (row) even though the job as 3 UnRead fields. But its returning 3 because its only doing what I'm asking. What I need it to do is just get the one Job (row) where any of the notes = UnRead.
I tried using Top 1, but that will only ever return one row and since I need it to return more than one job (row) it won't work.
Heres my attempt
DECLARE @UserID INT
SET @UserID = 4
SELECT User_Notes.BeenRead, Master_Jobs.By_Who, Master_Jobs.Next_Action, Master_Jobs.Due_Time, Master_Jobs.Due_Date, Master_Jobs.Contact,
Master_Jobs.Job_Title, Master_Jobs.JobID
FROM User_Notes INNER JOIN
Note ON User_Notes.FK_UN_NoteID = Note.NoteID INNER JOIN
Master_Jobs ON Note.FK_JobID = Master_Jobs.JobID
WHERE Note.FK_UserID = User_Notes.FK_UN_UserID AND
BeenRead = 'UnRead'
Thanks in advance
View 6 Replies
View Related
Dec 6, 2006
ok, so i have this table "SOLD_PRODUCTS" with this columns:
idProduct (int), quantitySold (int)
so i want to know how many products i have sold.
i have this query
Code:
SELECT idProduct, COUNT(idProduct) AS Total
FROM SOLD_PRODUCTS
GROUP BY idProduct
and get this
74 5
75 2
79 1
etc etc etc
this works correctly, but it doesnt counts the quantity sold, so i changed the query to
Code:
SELECT idProduct, quantitySold, COUNT(idProduct) AS Total
FROM SOLD_PRODUCTS
GROUP BY idProduct
but it crashes, mssql says i must add quantitySold to the group by clause.
but if i put the query
Code:
SELECT idProduct, quantitySold, COUNT(idProduct) AS Total
FROM SOLD_PRODUCTS
GROUP BY idProduct,quantitySold
i dont get the expected data, the idProducts appear more than once, they are no longer grouped by, the results in the count(idProduct) are wrong (i am not sure what they are counting now)
so now i dont understand how i can make my query, all i want is a query where in one collumn i have the product id, and in the other the quantity sold (that would be the count of all the product ids found multiplied by the quantity sold)
so now i am completelly lost, now i dont know what to do with my query.
any help pls pls pls!!!!
View 1 Replies
View Related
Jan 18, 2005
Hello To All @ Dev Shed,
I have three tables, say, A, B, and C. Both B and C contain/reference the primary key of A, ie B.a_id, and C.a_id. Multiple rows in B and multiple rows in C can have the same a_id. C and B have no relationships and essentially independant of each other.
I'm trying to find a single query (to prevent having to rewite function interfaces) that can return all the fields of A, the sum of a feilds in B, B.cost, where B.a_id = A.a_id and finially the count of C.a_id 's for where C.a_id = A.a_id.
The query I've been worlking on so far is as follows,
SELECT A.name, A.a_id, SUM (B.cost), COUNT ( DISTINCT C.a_id)
FROM A LEFT JOIN B USING (a_id) LEFT JOIN C USING (a_id)
GROUP BY A.a_id
This produces the correct result for the count of C.a_id (thanks to a DISTINCT) but the sum of B.cost is out by the factor of count C.a_id. I can see why this is happening but have completely run out of ideas. Group by on two columns may be? A strategically placed subquery? Is is even possible?
Any help would be much appreciated. Thanks in advance for your time.
Peter
PS I'm new to this forum thing so if you want the unsimplified query with all the full names just let me know and I'll post it.
View 2 Replies
View Related
Jul 16, 2006
Hello
I want to get the COUNT of
SELECT MAX(id) AS ids, Name, Version, Pack, Serial
FROM Products
GROUP BY Name, Version, Pack, Serial
SELECT COUNT(MAX(id) AS ids) AS countIds, Name, Version, Pack, Serial
FROM Products
GROUP BY Name, Version, Pack, Serial
doesnt work
thank you
View 4 Replies
View Related