Top N A Count Field?

Apr 10, 2008

I've got a stored proc which returns a location and corrosponding defects for that location. My matrix has the locations as rows and a count of defects as the data.

so...
LOCATION COUNT
--------------- ----------
AREA1 10
AREA2 5
AREA3 3
AREA4 2
AREA5 1


How can I manipulate the matrix (or table?) so I'll only show the Top 3 highest counts? I've tried screwing around with the Top N Filter, but as soon as I do =COUNT(Field!Defect.Value) on it the report wont run anymore. If the data came over in the above format that would make my life so much easier...but my matrix is all about aggregate data

Also I cant modify the stored proc as that dataset is used on multiple areas in the report


Any help would be great
Thanks,
Steve

View 4 Replies


ADVERTISEMENT

Count For Varchar Field - How To Get Distinct Count

Jul 3, 2013

I am trying to get count on a varchar field, but it is not giving me distinct count. How can I do that? This is what I have....

Select Distinct
sum(isnull(cast([Total Count] as float),0))

from T_Status_Report
where Type = 'LastMonth' and OrderVal = '1'

View 9 Replies View Related

How To Count This Field

Mar 5, 2007

I have a table like this. Each ConNo can have many boxes. The number of the box is an identfier, not a quantity.ie Box 3 = 1 box.A box may have a letter as a suffix or not.

I want to group by ConNo and total the boxes so I know how many Boxes are in each ConNo eg ConNo 200 5 boxes

TransId 1234
ConNo 200
BoxNo 1
BoxSuffix

TransId 1235
ConNo 200
BoxNo 1
BoxSuffix

TransId 1236
ConNo 200
BoxNo 2
BoxSuffix

TransId 1237
ConNo 200
BoxNo 2
BoxSuffix A

ConNo 200

BoxNo 1

TransId 1238
ConNo 201
BoxNo 1

TransId 1239
ConNo 201
BoxNo 1

TransId 1240
ConNo 201
BoxNo 3


TIA

View 8 Replies View Related

Update A Field With Count (*)

Jan 3, 2005

Hi,

I am trying to update a field in a temptable with the count of items in another table. To illustrate, CustomerID=23 and I want the number of occurences in the temp table. Here's the code which DOESN'T work:


INSERT INTO TempTable
(
CustomerID,
FirstName,
LastName,
DateAdded,
AlbumPicture,
LayoutCount
)
SELECT
Albums.CustomerID,
Customers.FirstName,
Customers.LastName,
DateAdded,
AlbumPicture,
COUNT(*) FROM Layouts WHERE Layout.customerID = Albums.CustomerID
FROM
Albums JOIN
Customers on (Albums.CustomerID=Customers.CustomerID)


Please take a look at the COUNT line. Here I want to count the occurences of a specific customerid in another table and put in into th LayoutCount field.

SQL server reports "Incorrect syntax near the keyword 'FROM'". Any ideas how to achieve this?

Many thanks!!

Eric

View 1 Replies View Related

Returning A Count Of A Certain Field

Nov 18, 2014

I want to get a count of how many PosAnswer are associated with the QuesToAsk 'List your top 5 favorite places'

This is the syntax I am using to achieve this, and it works, but wasn't sure if there was a better way (changing the data structure is unfortunately not an option in this situation). Here is my table structure

Code:
Create Table Test
(
QuesToAsk varchar(1000),
PosAnswer varchar(1000)

[Code] ....

And this is the syntax I use to get the count I am after

Code:
DECLARE @VariableName varchar(25)
DECLARE @FormattedVariableName varchar(25)
DECLARE @FieldCount int
SET @VariableName =

[Code] ....

View 5 Replies View Related

Get A Count On A Field For A Specific Value

Sep 13, 2013

I am attempting to combine to queries that I created and am not having success. I need to get a count on a field for a specific value and have to do this by gender and by an age range. So here is the query I came up with. I don't get any errors produced but I also don't get any results.

$query = "SELECT p1.sex, age_group, COUNT(CASE WHEN p4.q1 = 'Yes' THEN p4.q1 END) AS heart_attack FROM (select p1.sex,".
" CASE WHEN datediff(year, dateadd(day, -datepart(dayofyear, GetDate()), p1.birthday) , dateadd(day, -datepart(dayofyear, GetDate()), GetDate())) BETWEEN 11 AND 20 THEN '11-20'".
" WHEN datediff(year, dateadd(day, -datepart(dayofyear, GetDate()), p1.birthday) , dateadd(day, -datepart(dayofyear, GetDate()), GetDate()))

[code]....

View 8 Replies View Related

Displaying A 0 Value When There Is No Count Field

Sep 17, 2007

Hopefully this makes sense. I am new to SQL Reporting. My code is below. I am trying to get my query to display 0 when a category (prob_ctg.sym, does not have a Count value.

SELECT COUNT(*) AS Expr2, ISNULL(COUNT(*), '0') AS Total, CONVERT(varchar(20), Requestor.c_last_name) + ', ' + CONVERT(varchar(20),
Requestor.c_first_name, 112) AS Customer, Calls.ref_num, Calls.category, prob_ctg.sym, Calls.summary, DATEADD(s, Calls.open_date - 21600,
'1/1/70 12:00:00 am') AS OpenDT, DATEADD(s, Calls.close_date - 21600, '1/1/70 12:00:00 am') AS CloseDT, [Group].c_last_name AS GroupName
FROM ctct Requestor INNER JOIN
ctct [Group] INNER JOIN
call_req Calls ON [Group].id = Calls.group_id ON Requestor.id = Calls.customer INNER JOIN
int_org INNER JOIN
prob_ctg ON int_org.id = prob_ctg.organization ON Calls.category = prob_ctg.persid
WHERE (int_org.iorg_c_id LIKE '%400111%') AND (prob_ctg.del = 0) AND (DATEADD(s, Calls.open_date - 21600, CONVERT(DATETIME, '1970-01-01 00:00:00',
102)) BETWEEN @stdt AND @eddt)
GROUP BY Calls.category, prob_ctg.sym, Calls.summary, Calls.ref_num, Calls.open_date, Calls.close_date, [Group].c_last_name, int_org.iorg_name,
int_org.iorg_c_id, Requestor.c_last_name, Requestor.c_first_name

View 4 Replies View Related

Transact SQL :: Way To Count Changes In Value Of A Field

Oct 13, 2015

I want to avoid iterating through a table row by row and programmatically incrementing a counter,/I have define a view called Q2 with the following fields of interest:

Trial varchar(25)
BI int
Track int
CAT int

What I would like to do is partition by Trial, BI, and Track, and count the number of times CAT changes value. In Access, I would just iterate through a recordset inside a function, but I would like to see if there is a set based solution.Adding Sample Data and Output.

Trial     BI     Track     CAT
A         5      3           1
B         5      3           2

[code]...

View 5 Replies View Related

Count Of String Field

Jan 17, 2008



Hi All ,


I have one field in SQL Server Report Called Status which is text field.
that status can be "Abesent" , Late In", "Early Out" , "Early Out and Late in"
, its in table Like this.

Emp no | Name | Date | Time | Status
1 Kaisar 1-1-07 7:15 Late In
1 Kaisar 1-2-07 17:15 Early Out
1 Kaisar 1-4-07 - Absent
1 Kaisar 1-5-07 - Absent
1 Kaisar 1-6-07 - Absent

And So On......
----------------------------------------------------------------


i want to get count some thing like this

Total Of Absent : 3
Total Of Late in : 4
Total Of Early Out :5

any idea how can i do this ?








View 5 Replies View Related

Sum Or Count Value Of Field In Stored Procedure

Apr 19, 2005

How can i create a stored procedure that count or sum value of field
e.g.

               
f1      f2    
f3    f4    f5
 record     1      
1      2     
3     1
 
and get answer  like this   1=4  - 2=1 -  3=1

 

View 1 Replies View Related

Count Unique Rows In Each Field

Jul 24, 2013

I have a table in Access 2007 that has about 30 field names and I want to have a count of how many unique rows there are in each field. I want to have these results put into another table that will just have the field name and then the count of how many unique rows there are.

I have code in VBA that will loop through my SQL and change out the field name, but I can't seem to get the SQL right before I can start looping it. For just one field name this would be what I have to count the unique names...

So far I have this:

INSERT INTO newtable
COUNT(*) FROM (SELECT Raw_Table.FieldName, COUNT(Raw_Table.FieldName) AS CountOfFieldName
FROM Raw_Table
GROUP BY Raw_Table.FieldName);

And its not going too well.

View 1 Replies View Related

Count Values Of 2 Field On Particular Date

May 7, 2015

I want to count the values of 2 field on particular date

I have user table with 3 field

1.from_userid
2.to_userid
3.Date

Now i want to count the no. of files from_userid have send, no. of files to user_id have received on particular day. The data is like this

From_userid to_userid date
3953 6274 10/22/2014
3953 6152 10/22/2014
1112 2710 10/22/2014
3953 1851 10/23/2014
3953 4302 10/23/2014
4302 2710 10/23/2014

View 2 Replies View Related

Display (field) But Only Count Managers

May 8, 2007

I need to figure out the number of managers without listing them. Label the column Number of Managers.

any help is appricated.


Number of Managers
-------------------------
6

View 3 Replies View Related

Updating Field Based On Record Count

Oct 18, 2004

I am trying to write a stored procedure that updates a value in a table based on the sort order. For example, my table has a field "OfferAmount". When this field is updated, I need to resort the records and update the "CurrRank" field with values 1 through whatever. As per my question marks below, I am not sure how to do this.


Update CurrRank = ??? from tblAppKitOffers
where appkitid = 3 AND (OfferStatusCode = 'O' OR OfferStatusCODE = 'D')
ORDER BY tblAppKitOffers.OfferAmount Desc


All help is greatly appreciated.

View 2 Replies View Related

COUNT Field Incorrect - Error Message

Sep 14, 2000

I am trying to run the plan analyser on a SQL query that I cut and pasted from a Siebel trace. I get the following error

[Microsoft][ODBC SQL Server Driver]COUNT field incorrect

There is no count in the SQL query, and there doesn;t seen to be a message number to look up, anyone got any ideas?
I have done the obvious stuff like changing the DB name in the query, but to no avail....

Cheers

Mike

View 1 Replies View Related

COUNT Field Incorrect Or Syntax Error.

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

Count Same Field Mutiple Times With Different Criteria

May 12, 2006

Is it possible to count the same field with different criteria. It would be something like this.

car_table
car_id
car_name
car_brand

So you would execute a statement which would count(car_brand) with two different criteria.

I am not sure if this is possible or if there is another way to approach it.

View 1 Replies View Related

Table With 4 Columns - Count Field Is Null

Jan 22, 2015

I have a table with 4 column in below

Total amount = 1000
salemancode1 = space
salemancode2 = Staff-99
salemancode3 = space
salemancode4 = staff-88

How I can write a one query statement to do this, we expect to count how many salemancode is not space and count the number of salesman to over the total amount.

total amount / (no_of_saleman) as commission
the result is 1000/ 2 the commission is $500.

View 1 Replies View Related

SQL Server 2012 :: Record Count Of Column Field

Oct 30, 2014

I have created table in which there are four columns (id, date, parcelname, parcelnumber) and 10 rows. I want to count record of the column parcelnumber but condition that, in between two different dates the record should be counted.

View 9 Replies View Related

SUM Of Report Field With Expression Which Has COUNT Aggregate Function

Jun 20, 2007

Hi everyone,



I have created a report which has 3 groups. The report output as shown below. I am having trouble getting the SUM of Total Credtis for each Org.

Can't seem to get the total 42 and 16 (highlighted), but can get total unists 11 and 13. I get expression contains aggregate function. This is because Units assessed is the Count of IDs (details hidden from the report).



Report has three groups Org , Assessor and Unit.

Can someone please help me with this?

Appreciate help.

Thank you,

Ski





Org 1(Group1)

Unit Credits Units Assessed(# of Trainees) TotalCredits



Assessor 1 Unit 1 2 4 (Count of Ids) 8 (2*4)

Assessor 2 Unit 2 1 2 2 (1*2)

Assessor 3 Unit 3 5 2 10 (5*2)

Unit 4 2 1 2

Assessor 4 Unit 5 10 2 20

--------------------------------------------------------------------------------------------------------

11 42 -----------------------------------------------------------------------------------------------------------



Org 2

Assessor 3 Unit 1 2 3 6

Assessor 4 Unit 6 1 10 10

--------------------------------------------------------------------------------------------------------

13 16

--------------------------------------------------------------------------------------------------------









View 4 Replies View Related

Transact SQL :: How To Update A Field And Insert Increment Count

May 28, 2015

I want to update a field and in this field insert a increment count, for example:

When I make, "Select * from Users order by User" displays:

User1  |  NULL
User1  |  NULL
User1  |  NULL
User2  |  NULL
User2  |  NULL

and I want to do this:

User1  |  1
User1  |  2
User1  |  3
User2  |  1
User2  |  2

how to do this?

View 7 Replies View Related

Trigger To Count Words In Field On Update,insert

Aug 28, 2007

I want to create a trigger that, when a field is updated or a record is inserted, counts the number of words in "field1", inserting this numeric value into another field in the same table. What would be the most efficient, fastest method for doing this?

View 15 Replies View Related

SQL 2012 :: How To Count Instances Of Each Word Throughout Comments Field Across The Table

Oct 21, 2015

I have to count the number of instances of each word in the Comments column throughout the table using SQL Server. Eg:

Row# Comments
1 I like working on SQL
2 I enjoy sleeping and like watching TV

So the output should be :

Word Count
I 2
like 2
working 1
on 1
SQL 1
.......

Any way to get this count using MS SQL?

View 5 Replies View Related

T-SQL (SS2K8) :: Wrap Varchar Field Based On Character Count And Spaces

Dec 8, 2014

Because of a limitation on a piece of software I'm using I need to take a large varchar field and force a carriage return/linebreak in the returned sql. Allowing for a line size of approximately 50 characters, I thought the approach would be to first find the 'spaces' in the data, so as to not split the line on a real word. achieve.

--===== Simulate a passed parameter
DECLARE @Parameter VARCHAR(8000)
SET @Parameter = (select a_notes
from dbo.notestuff as notes
where a_id = '1')

[Code] .....

View 5 Replies View Related

Transaction Count After EXECUTE Indicates That A COMMIT Or ROLLBACK TRANSACTION Statement Is Missing. Previous Count = 1, Current Count = 0.

Aug 6, 2006

With the function below, I receive this error:Error:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.Function:Public Shared Function DeleteMesssages(ByVal UserID As String, ByVal MessageIDs As List(Of String)) As Boolean        Dim bSuccess As Boolean        Dim MyConnection As SqlConnection = GetConnection()        Dim cmd As New SqlCommand("", MyConnection)        Dim i As Integer        Dim fBeginTransCalled As Boolean = False
        'messagetype 1 =internal messages        Try            '            ' Start transaction            '            MyConnection.Open()            cmd.CommandText = "BEGIN TRANSACTION"            cmd.ExecuteNonQuery()            fBeginTransCalled = True            Dim obj As Object            For i = 0 To MessageIDs.Count - 1                bSuccess = False                'delete userid-message reference                cmd.CommandText = "DELETE FROM tblUsersAndMessages WHERE MessageID=@MessageID AND UserID=@UserID"                cmd.Parameters.Add(New SqlParameter("@UserID", UserID))                cmd.Parameters.Add(New SqlParameter("@MessageID", MessageIDs(i).ToString))                cmd.ExecuteNonQuery()                'then delete the message itself if no other user has a reference                cmd.CommandText = "SELECT COUNT(*) FROM tblUsersAndMessages WHERE MessageID=@MessageID1"                cmd.Parameters.Add(New SqlParameter("@MessageID1", MessageIDs(i).ToString))                obj = cmd.ExecuteScalar                If ((Not (obj) Is Nothing) _                AndAlso ((TypeOf (obj) Is Integer) _                AndAlso (CType(obj, Integer) > 0))) Then                    'more references exist so do not delete message                Else                    'this is the only reference to the message so delete it permanently                    cmd.CommandText = "DELETE FROM tblMessages WHERE MessageID=@MessageID2"                    cmd.Parameters.Add(New SqlParameter("@MessageID2", MessageIDs(i).ToString))                    cmd.ExecuteNonQuery()                End If            Next i
            '            ' End transaction            '            cmd.CommandText = "COMMIT TRANSACTION"            cmd.ExecuteNonQuery()            bSuccess = True            fBeginTransCalled = False        Catch ex As Exception            'LOG ERROR            GlobalFunctions.ReportError("MessageDAL:DeleteMessages", ex.Message)        Finally            If fBeginTransCalled Then                Try                    cmd = New SqlCommand("ROLLBACK TRANSACTION", MyConnection)                    cmd.ExecuteNonQuery()                Catch e As System.Exception                End Try            End If            MyConnection.Close()        End Try        Return bSuccess    End Function

View 5 Replies View Related

Analysis :: Count Function Taking More Time To Get Count From Parent Child Dimension?

May 25, 2015

below data,

Countery
parentid
CustomerSkId
sales

A
29097
29097
10

A
29465
29465
30

A
30492
30492
40

[code]....
 
Output

Countery
parentCount

A
8

B
3

c
3

in my count function,my code look like,

 set buyerset as exists(dimcustomer.leval02.allmembers,custoertypeisRetailers,"Sales")
set saleset(buyerset)
set custdimensionfilter as {custdimensionmemb1,custdimensionmemb2,custdimensionmemb3,custdimensionmemb4}
set finalset as exists(salest,custdimensionfilter,"Sales")
Set ProdIP as dimproduct.dimproduct.prod1
set Othersset as (cyears,ProdIP)
(exists(([FINALSET],Othersset,dimension2.dimension2.item3),[DimCustomerBuyer].[ParentPostalCode].currentmember, "factsales")).count

it will take 12 to 15 min to execute.

View 3 Replies View Related

Transact SQL :: Return Field When A Field Contains Text From Another Field

Aug 25, 2015

I'm new to SQL and I'm trying to write a statement to satisfy the following:

If [Field1] contains text from [Field2] then return [Field3] as [Field4].

I had two tables where there were no matching keys. I did a cross apply and am now trying to parse out the description to build the key.

View 8 Replies View Related

How To Add Date Field And Time Field (not Datetime Field )

May 4, 2006

Good morning...

I begin with SQL, I would like to add a field that will be date like 21/01/2000.

Actually i find just "datetime" format but give me the format 21/01/2000 01:01:20.

How to do for having date and time in two different field.

Sorry for my english....

Cordially

A newbie

View 3 Replies View Related

In SQL 2000 Can I Use Count() To Count A Column?

Nov 26, 2007

I use SQL 2000
I have a Column named Bool , the value in this Column is  0ã€?0ã€?1ã€?1ã€?1
I no I can use Count() to count this column ,the result would be "5"
but what I need is  "2" and "3" and then I will show "2" and "3" in my DataGrid
as the True is  2 and False is 3
the Query will have some limited by a Where Query.. but first i need to know .. how to have 2 result count
could it be done by Count()? please help.  
thank you very much
 

View 5 Replies View Related

Table Row Count + Index Row Count

Jul 23, 2005

SQL 2000I have a table with 5,100,000 rows.The table has three indices.The PK is a clustered index and has 5,000,000 rows - no otherconstraints.The second index has a unique constraint and has 4,950,000 rows.The third index has no constraints and has 4,950,000 rows.Why the row count difference ?Thanks,Me.

View 5 Replies View Related

Obtain Unit Percent With Unit Count Divided By Total Count In Query

Aug 21, 2007

The following query returns a value of 0 for the unit percent when I do a count/subquery count. Is there a way to get the percent count using a subquery? Another section of the query using the sum() works.

Here is a test code snippet:


--Test Count/Count subquery

declare @Date datetime

set @date = '8/15/2007'


select
-- count returns unit data
Count(substring(m.PTNumber,3,3)) as PTCnt,
-- count returns total for all units

(select Count(substring(m1.PTNumber,3,3))

from tblVGD1_Master m1

left join tblVGD1_ClassIII v1 on m1.SlotNum_ID = v1.SlotNum_ID

Where left(m1.PTNumber,2) = 'PT' and m1.Denom_ID <> 9

and v1.Act = 1 and m1.Active = 1 and v1.MnyPlyd <> 0

and not (v1.MnyPlyd = v1.MnyWon and v1.ActWin = 0)

and v1.[Date] between DateAdd(dd,-90,@Date) and @Date) as TotalCnt,
-- attempting to calculate the percent by PTCnt/TotalCnt returns 0
(Count(substring(m.PTNumber,3,3)) /

(select Count(substring(m1.PTNumber,3,3))

from tblVGD1_Master m1

left join tblVGD1_ClassIII v1 on m1.SlotNum_ID = v1.SlotNum_ID

Where left(m1.PTNumber,2) = 'PT' and m1.Denom_ID <> 9

and v1.Act = 1 and m1.Active = 1 and v1.MnyPlyd <> 0

and not (v1.MnyPlyd = v1.MnyWon and v1.ActWin = 0)

and v1.[Date] between DateAdd(dd,-90,@Date) and @Date)) as AUPct
-- main select

from tblVGD1_Master m

left join tblVGD1_ClassIII v on m.SlotNum_ID = v.SlotNum_ID

Where left(m.PTNumber,2) = 'PT' and m.Denom_ID <> 9

and v.Act = 1 and m.Active = 1 and v.MnyPlyd <> 0

and not (v.MnyPlyd = v.MnyWon and v.ActWin = 0)

and v.[Date] between DateAdd(dd,-90,@Date) and @Date

group by substring(m.PTNumber, 3,3)

order by AUPct Desc


Thanks. Dan

View 1 Replies View Related

Inserted Rows Count From SSIS Not Like Table Rows Count

Jun 25, 2007

Hi all



i using lookup error output to insert rows into table

Rows count rows has been inserted on the table 59,123,019 mill

table rows count 6,878,110 mill ............................



any ideas

View 6 Replies View Related

Count(*) Vs Count(columnname)

Aug 28, 2007

 Is there a difference in performance when using count(*) or count(columnname)?

View 10 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved