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


ADVERTISEMENT

Breakout Records Based On UNIT Total Without Cursor

Jan 30, 2008

I have a set of revenue records where there is a UNIT column and a REVCHARGE column. What I need to do is breakout the records into single records where the unit count is > 1 and calc the actual charge:

Ex:

Units REVCHG FIELD_A FIELD_B .....
3 3.00 ABCD EFGH

Needs to be converted to:

Units REVCHG FIELD_A FIELD_B .....
1 1.00 ABCD EFGH
1 1.00 ABCD EFGH
1 1.00 ABCD EFGH

The calc is obvious but how can I do this with a cursor but would like to do it without a cursor if possible? Anybody got an idea?

Thanks.

View 6 Replies View Related

Getting Total Count From Query

Sep 21, 2013

I have to write a query to get the count() of the customer who has max sales in the last 6 months.my query is

Select Inv_Cust,Count(Inv_Cust) as Salescount From Inv_Header Group By Inv_Cust,Inv_Date Having Inv_Date Between MIN(Inv_Date) And DATEADD(MM,6,min(Inv_Date))
which gives me a result like
inv_cust ' Salescount

[code]...

How can I modify my existing query to get this.

View 2 Replies View Related

Getting Total Row Count For Complex Query Using CTE

Apr 26, 2007

I have a query that uses a CTE which looks similar to this

WITH cte_Products AS
(SELECT SELECT
ROW_NUMBER() OVER (ORDER BY ProductName ASC) AS RowNum,
RANK() OVER (ORDER BY id DESC) AS rank,
FROM Products
WHERE SomeColumn = @SomeVariable)
SELECT rownum,
columns,
(SELECT COUNT(*) FROM cte_Product) AS TotalRowCount
FROM cte_Product AS products
WHERE Rank <= @LastXItems
AND RowNum BETWEEN (@StartRowIndex + 1) and (@StartRowIndex + @MaximumRows)
ORDER BY RowNum

The (SELECT COUNT(*) FROM cte_Product) AS TotalRowCount is in there because I need the total row count that is queried by the CTE. But I feel like this is an inefficient way of doing this. I would just split out the query for the total row count, but then I have to do another sub query to get the rank again since rank is calculated using the Rank method. Does anyone have any ideas of how best to do this?

View 3 Replies View Related

Trying To Return Total Record Count With Query

Feb 26, 2007

I'm trying to return the total records with my query, but I'm getting the following error:

"Item cannot be found in the collection corresponding to the requested name or ordinal."

Here's my query:


set rsFind = conn.Execute ("Select Count(Incident_ID) as TotalCount, Incident_ID, ProblemDescriptionTrunc, Action_Summary, RootCause, Problem_Solution002, " _
& " AssignedTechnician, DATEADD(s, dbo.TTS_Main.DateClosed, '1/1/1970') AS DateClosed, DATEADD(s, dbo.TTS_Main.Date_Opened, '1/1/1970') AS DateOpened, AssignedGroup From tts_main Where ProblemDescriptionTrunc LIKE '%" & prob & "%' And Last_Name LIKE '%" & l_name & "%' " _
& " AND AssignedTechnician LIKE '%" & assigned_tech & "%' And Incident_ID LIKE '%" & ticketnum & "%' AND assignedgroup LIKE '%" & assigned_group & "%' " _
& " Order By DateClosed DESC ")

<%response.write rsfind("TotalCount")%>


Thanks for any help!
Dale

View 10 Replies View Related

Unit Testing

Oct 1, 2005

I've started researching on Unit Testing and I must admitI had never heard of Unit Testing until a couple of monthsago. Obviously I am interested in Unit Testing StoredProcedures.I read the TSQLUnit documentation (not all of it) and i also raninto a newsgroup post saying TSQLUnit is very small comparedto NUnit. The conclusion I am making out of this post is thatI should rather spend time resarching/reading about NUnit thanTSQLUnit. Is that a good assessment?I would like to you what you use and if you use actuallyUnit Testing or some other method? I ran into White Box/Black BoxQA testing. All these are new to me. Any good place to read about"Extreme Programming"? I ran into one link that I saved it at work.That's one place i will read more.Any links, documentation or books you would suggest?I searched Amazon and I didn't find anything interestingregarding SQL Server and Stored Procedures.Thank you

View 1 Replies View Related

Unit Testing

Jun 20, 2005

Well was wondering this weekend. How do you do unit testing with SSIS? Is anyone trying it?

View 9 Replies View Related

How Do I Obtain The Row Count

Mar 1, 2001

I'm working on a search engine right now, and I am querying out a set amount of information at one time. How can I grab the last row count of a query, and use that as a starting point, or index when a "Next 100" is pressed. For instance, a person searches through a user table, but only wants 25 users at a time. So the beginning index is 0 to 25. In my query, I have "SELECT TOP 25 from users", but now when the person searching want's to move to the next 25 users, so the index would be 26 to 50, how can I hold the last row displayed? It gets a little more complex also, if a user is searching by last name, the rows will be staggered. Is there a SQL function which will grab the number of the last row displayed? I've looked through the SQL Book, and was unable to find a function that does this, or anything close to it. I hope I made sense of this question, if you need more information, email me and I will try to clarify. Thank you for any information or hints.

View 1 Replies View Related

How To Use Unit Test In SSIS

May 8, 2007

I build a SSIS Package in Visual Studio 2005 , but i don't know how to test it automated?

View 7 Replies View Related

Nested SQl With Count, Percent And Joins: How?!

May 14, 2008

Hiya,
I have a need for a complex SQL statement to provide reporting information, but the SQL is way over my head and although I have some of the elements, I can't seem to pull them together to create a working SQL statement.
My database structure is as outlined below:

tblDef
------
ID IRVitems
ABC A1,A2,A3,A4,A5

tblIRV
------
ID IRVvalues
001 1,5,text1,10,3
002 2,1,text2,1,3
003 2,4,text3,1,1
004 1,4,text4,4,1
005 1,2,text5,4,1

tblLabel
--------
lblID lblVALUE lblTXT
A1 1 AAA
A1 2 BBB

I currently query tblDef to get IRVitems and in turn then query the other two tables to get statistical information to present in a report (via ASP).

For each item returned from IRVitems, I would like to report the spread and frequency of different values as follows:

A1
Value Label Count Percent
1 AAA 3 60
2 BBB 2 40

and then for A2, etc (although missing out A3 as it is a text item, but I can deal with that via ASP code beforehand). I would expect to have to hit the DB for each of the IRVitems (so once for getting the data for A1, againfor A2, etc).

I was provided a great bit of code to use SUBSTRING and GROUP BY to get this data (thanks zuomin), but I didn't consider the possible text values or numbers >9 when defining what I was trying to do (to be fair, they're new requirements):

SELECT SUBSTRING(IRVvalues, 1, 1) AS Value, COUNT(ID) AS Count
FROM tblIRV
GROUP BY SUBSTRING(IRVvalues, 1, 1)
ORDER BY value

which returns like this:

Value Count
1 187
2 163
3 2

Can I do a similar query to get all the info I need in one go? I saw the articale on a user-defined 'split' function (http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput&referringTitle=Home) that can be used to split up the IRVvalues string to access the position I need in the array, but I'm a little clueless on how to then embed that into a SQl statement.
Can anyone point me in the right direction please?

View 3 Replies View Related

Adding Columns With Different Time Unit

Oct 29, 2014

I have three different columns, hour(s), min(s), sec(s)

I can add it up, but will like to convert it into. hrs, mins and sec.

this is how, i am adding it up into seconds.

SELECT ((TotalTimeSpentHrs*60*60)+(TotalTimeSpentMin*60)+(TotalTimeSpentSec))AS totaltime
FROM EST1

How can I convert the total seconds, so that i can input the result in a new column.

View 1 Replies View Related

Custom Component And Unit Testing

Nov 11, 2007



Hello.


I want to test my custom component with unit tests and i thought i must only initilize the component to play around with it. But when i calling the ProviderComponentProperties method and there the RemoveAllInputsOutputsAndCustomProperties method a NullReference exception is thrown. After debugging the test i had seen that the ComponentMetaData of the component is null. Is there a way to initilize the ComponentMetaData?

The Code of the Component looks like this:




Code Block
[DtsPipelineComponent(
DisplayName = "TestSourceAdapter",
ComponentType = ComponentType.SourceAdapter,
IconResource = "TestSourceAdapter.TestSourceAdapter.ico"
)]
public class TestSourceAdapter: PipelineComponent
{

public override void ProvideComponentProperties()
{

RemoveAllInputsOutputsAndCustomProperties();

IDTSOutput90 output = ComponentMetaData.OutputCollection.New();
output.Name = "TestSourceAdapter";


ComponentMetaData.OutputCollection

["TestSourceAdapter"].ExternalMetadataColumnCollection.IsUsed = true;

ComponentMetaData.ValidateExternalMetadata = false;
ComponentMetaData.UsesDispositions = true;
ComponentMetaData.Name = "TestSourceAdapter";
ComponentMetaData.Description = "TestSourceAdapter";


ReinitializeMetaData();
}


...
}




And in test i call only this




Code Block
TestSourceAdapter testAdapter = new TestSourceAdapter();
_testAdapter.ProvideComponentProperties();





i hope anyone can help

regards
kai

View 1 Replies View Related

File Allocation Unit Size

Mar 20, 2007

This is a question that has always intrigued me: what is the ideal File Allocation Unit Size for a disk holding only data or index pages on a server running SQL Server? It seems to me that 8,192 would be the ideal size as it would enable the system to gobble up an entire page in one go. Any ideas?

View 18 Replies View Related

Time Format - What's The Smallest Unit SQL 2005 Can Take?

May 2, 2007

saw my AS400 has this time stamp: 2007-05-02-11.29.56.811195

is SQL2005 able to have time stamp to this details?

View 1 Replies View Related

How To Find OrderID And Maximum-price Unit Of Each Order

Jun 13, 2013

How to select the orderID, order date and the maximum-price unit of each order in the below tables in 2 ways:

1-using correlated sub-query
2-not using correlated sub-query

I only selected orderID, order date and the maximum price of each order but not the unit name.This is my query:

Code:
SELECT dbo.[Order Details].OrderID, Max(dbo.[Order Details].UnitPrice)as MaxUnitprice, dbo.Orders.OrderDate
FROM dbo.[Order Details] INNER JOIN
dbo.Products ON dbo.[Order Details].ProductID = dbo.Products.ProductID INNER JOIN
dbo.Orders ON dbo.[Order Details].OrderID = dbo.Orders.OrderID
GROUP BY dbo.[Order Details].OrderID, dbo.Orders.OrderDate

View 6 Replies View Related

Clearing All Messages From A Queue - For Automated Unit Test

Jun 4, 2007

Hi,

I am developing automated .Net Unit Tests, and as a prerequisite of each test, I would like to clear the service broker queues of any messages. Executing the

RECEIVE * FROM statement appears to only return a message at a time, and not all as I expected. Any ideas on how to make this happen, besides not having to delete the queues and then having to rebuild them?

Thanks,Eugen

View 3 Replies View Related

What Are To Be Installed At The Production Unit To Deploy A Package Created ?

Nov 14, 2006

Hi friends,

Can anybody tell what all are required for the deployment of a package.

I read from some article that to deploy ur package SSIS runtime and .Net framework should be installed first

and 1)it is not necessary to install sql server 2005. if so Is it True .?

2)whether the ssis runtime is freely available as independent installation package like .Net framework





View 5 Replies View Related

Total Record Count - Pagination With Total Rows

Jul 26, 2013

My table contains 1000 records,

I need to know the total record count with the below paging query

SELECT EmpName,Place
FROM EmplyeeDetails ORDER BY Place
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;

How to get?

View 2 Replies View Related

SQL 2012 :: Error Occurred While Attempting To Drop Allocation Unit

May 4, 2015

Since a couple days, we are getting this message the errorlog of one of our SQL2012 server

LogEntry: Error [36, 17, 145] occurred while attempting to drop allocation unit ID 451879652360192 belonging to worktable with partition ID 451879652360192.
(version Microsoft SQL Server 2012 - 11.0.5058.0 (X64))

I am wondering what is the best way trying to troubleshoot this issues? I do not know from which of out database this is coming.

View 6 Replies View Related

Transact SQL :: Function To Return Unit Price Based On Various Criteria

Apr 30, 2015

We were asked to create an SQL function to return a unit price based on various criteria. The function works fine except for the tiered pricing (use of BillingPriceTable) calculation.  What we need to do is break up the total quantity passed to the function and return the total of prices found.  In our example, we passed a quantity of 9,721 units and need to return a total price of 231.92 using the table below.

Low Qty    High Qty    Fee        Actual Qty        Price
0                  7500        0.025            7500           187.50
7501           15000        0.020            2221          44.42

Below is the table definition that we have to work with (ugghh).

CREATE TABLE [dbo].[BillingPriceTable](
[PriceTableID] [int] IDENTITY(1,1) NOT NULL,
[entity] [varchar](4) NULL,
[PriceTableCode] [varchar](10) NULL,
[PriceTableName] [varchar](40) NULL,

[Code] ....

What we have so far is shown below.  The columns that start with bdxx are the "High Qty" values and the columns that start with prxx are the price for that quantity range.  So, the current SELECT is shown below and it returns the price based on the entire qty of 9,721 and returns a unit price of 0.020 and should return 0.023857628

The current SELECT is shown below and is returning 0.020 which is the fee for the total rather than calculating the fee twice, once for the 0-7500 and again for the 7501-15000 (actually 7501-9721). Two things came to mind, one was a WHILE loop and the other was possibly a ranking function of some sort. 

ALTER FUNCTION [dbo].[fn_GetPrice]
(
@plincdvarchar(3),
@pgrpcodevarchar(4),
@pitmcodevarchar(4),
@qtydecimal(10,1) = 1,
@corpnbrvarchar(9)
)

[Code] ....

View 9 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

Total No Of Row Count

Sep 25, 2007

Hi,



I am using a foreach file to loop through mdb files kept in a folder and then transfer them to Sql server.

I want to do the following -



Sum the total no. of rows in mdb while the package executes

Sum the total no of rows transferred to Sql server.

Write them to a database (InitialRowCnt, FinalRowCnt, PackageNm, UserNm)


Note: Total = Total rows in all mdb files. so if there are 10 mdb files with 10 rows each, total = 100.


I saw a RowCount transformation..but just dont know where to place and what to do with it.



thanks

View 2 Replies View Related

Get Records With A Count Total

Feb 14, 2008

Hello, I am having problems with this query below:
 1 SELECT Table1.Email AS Email,
2 Table2.UserName AS Username,
3 Table3.Members_Paid AS Paid,
4 (SELECT DISTINCT COUNT(*)
5 FROM Table3 AS e JOIN Table3 AS m
6 ON e.Members_Sponsor = m.Members_ID
7 WHERE (e.Members_Sponsor = m.Members_ID)) AS TotalRecords
8 FROM Table1 INNER JOIN
9 Table2 ON Table1.UserId = Table2.UserId INNER JOIN
10 Table3 ON Table2.UserId = Table3.UserID
11 WHERE (Table3.Members_Sponsor = @UserId)Basicly what I am trying to do is get all members that belong to a certain manager along with those members count total of members they have below them.The code above is giving me the count of the first member only, not different counts for each member.Hope you understand what I am trying to say and do here. Hope someone can help me out cause this hase been driving me crazy for a few days now.
 

View 1 Replies View Related

How To Create Total Time, Count It

Aug 29, 2005

i hv a problem in sql,

i) if in data hv time_start, time_end, date , id, how i can calculate the total time for very sesion user login

ii) how to make it if the total come out hv same id(may be two id hv two diffrent total), i want make it just one id then the total time...

post me at jeffliew2001@yahoo.com

View 6 Replies View Related

Count The Total Number Of Results Returned

May 17, 2007

Iam using front page to dispalay my results.

At the bottom it shows me 1/10 i.e 1st page of 10 pages.

but what do i do if i want it to be shown as 1-10 out of 100 (if each page contains 10 results).

or it would be really good if i get count of both no. of recors as well as no. of pages.

View 2 Replies View Related

Select TOP 1 And Count Total Records At Same Time

Jun 7, 2012

I have a Select TOP 1 statement which works fine, but i also want to count the total records at the same time. This is my SQL

Code:
SELECT TOP (1) dbo.ClientOffers.ProductID, dbo.ClientOffers.ClientID, dbo.Offers.Offertext, dbo.Offers.Offerlink, dbo.Offers.Image, dbo.Offers.Cost
FROM dbo.ClientOffers INNER JOIN
dbo.Offers ON dbo.ClientOffers.OfferID = dbo.Offers.OfferID
WHERE (dbo.ClientOffers.ProductID = 1284) AND (dbo.ClientOffers.ClientID = 0)

How do i also count the total records?

View 7 Replies View Related

Running Total Count In Stored Procedure

Jul 20, 2005

in my procedure, I want to count the number of rows that have erroredduring an insert statement - each row is evaluated using a cursor, soI am processing one row at a time for the insert. My total count tobe displayed is inside the cursor, but after the last fetch is called.Wouldn't this display the last count? The problem is that the count isalways 1. Can anyone help?here is my code,.... cursor fetchbegin ... cursorif error then:beginINSERT INTO US_ACCT_ERRORS(ERROR_NUMBER, ERROR_DESC, cUSTOMERNUMBER,CUSTOMERNAME, ADDRESS1, ADDRESS2, CITY,STATE, POSTALCODE, CONTACT, PHONE, SALESREPCODE,PRICELEVEL, TERMSCODE, DISCPERCENT, TAXCODE,USERCOMMENT, CURRENCY, EMAILADDRESS, CUSTOMERGROUP,CUSTINDICATOR, DT_LOADED)VALUES(@ERRORNUM, @ERRORDESC,@CUSTOMERNUMBER, @CUSTOMERNAME, @ADDRESS1, @ADDRESS2, @CITY,@STATE, @POSTALCODE, @CONTACT, @PHONE, @SALESREPCODE,@PRICELEVEL, @TERMSCODE, @DISCPERCENT, @TAXCODE,@USERCOMMENT, @CURRENCY, @EMAILADDRESS, @CUSTOMERGROUP,@CUSTINDICATOR, @DTLOADED)SET @ERRORCNT = @ERRORCNT + 1END --error--FETCH NEXT FROM CERNO_US INTO@CUSTOMERNUMBER, @CUSTOMERNAME, @ADDRESS1, @ADDRESS2, @CITY, @STATE,@POSTALCODE, @CONTACT,@PHONE,@SALESREPCODE, @PRICELEVEL,@TERMSCODE,@DISCPERCENT, @TAXCODE, @USERCOMMENT, @CURRENCY,@EMAILADDRESS,@CUSTOMERGROUP, @CUSTINDICATOR, @DTLOADED--IF @ERRORCNT > 0INSERT INTO PROCEDURE_RESULTS(PROCEDURE_NAME, TABLE_NAME, ROW_COUNT,STATUS)VALUES('LOAD_ACCOUNTS', 'LOAD_ERNO_US_ACCT', @ERRORCNT, 'FAILEDINSERT/UPDATE')END -- cursorCLOSE CERNO_USDEALLOCATE CERNO_US

View 1 Replies View Related

How To Get Total Page Count For Individual Groups

Aug 3, 2007

Hello,



I have report in which I have created groups base on the customer name. Can anybody please tell me how to get the total page counts for the individual group? I have page break after every new group and I am able to reset page count to 1 when new group start but I am getting the total number of pages for a particular group.



For ex, let say I have 4 groups, 1 group has 3 page, 2 group has 2 pages and 3 group has 6 page and 4th group has 7 pages I need something like,



For 1st group

'Page 1 of 3€™ when user click next page it should be 'Page 2 of 3' etc



Similarly for other groups as wll.



Thanks!

View 3 Replies View Related

Transact SQL :: Total Count Of Table Rows

Sep 15, 2015

I have a question regarding the total count of the table rows

Select count (name) from test. Lets say I have got 200 count. And Select count (lastname) from test1.I have got 200.And this counts I should store it in "There are nn name items awaiting your attention and nn pending lastname's awaiting your approval".

So now I have to store the count in 'nn'.

View 5 Replies View Related

Get Total Count And Top N Rows In Single Call

Dec 3, 2007



Hi,

I want to return the total number of rows and top n records from my query. Is it possible to do this by simply running a single query. My query is dynamic so I can not create any temp table or table variables.

Bacially I want to eliminate 2 calls for sp_executesql

Set @ColumnCount = "Count(*)"
Set @Columns = " Top 100 a,b,c"
Set @Filter = "a = 1001"

Set @sql = "select " + @ColumnCount + " FROM TABLEA WHERE " + @Filter
sp_executesql @Sql

Set @sql = "select " + @Columns + " FROM TABLEA WHERE " + @Filter
sp_executesql @Sql

Thanks
Pun

View 3 Replies View Related

Distinct Count With Null Values (grand Total)

May 9, 2007

Hello,

I have a DB of professors and information related with them. I created the cube, it consist of:
Measures:
Measure group Professors:
Amount of projects (COUNT proj_id)
Amount of pulications (COUNT pub_id)
Amount of e_books (COUNT book_id)
--------------
Measure group Projects:
Distinct amount of projects (DISTINCT COUNT proj_id)
--------------
Measure group Publications:
Distinct amount of publications (DISTINCT COUNT pub_id)
--------------
Measure group E_books:
Distinct amount of e_books (DISTINCT COUNT book_id)
--------------
Calculated measures:
Amnt_Projects
iif ([Measures].[ Amount of projects ] = 0 OR [Measures].[ Amount of projects] = NULL,0,[Measures].[ Distinct amount of projects])
Amnt_Publications
(similar to the above one)
Amnt_E_books
(similar to the above one)
---------------------------
Dimensions:
dimPROFESSORS
- prof_id
-surname
-name
-gender
dimPROJECTS
- proj_id
-type name
-name
dimPUBLICATIONS
- pub_id
-type name
-name
dimE_BOOKS
- book_id
-name
Date_Projects
-date_id
-years
Date_Publications
-date_id
-years
Date_E_books
-date_id
-years


For example, when I browse the cube:
prof_id____Amount of projects___Distinct amount of projects___Amnt_Projects
1032------------------- 30 --------------------------1----------------1
1070-------------------90 --------------------------2----------------2
1111-------------------0 ---------------------------1----------------0
1137-------------------0 ---------------------------1----------------0
1234-------------------1404--------------------------9----------------9
1721-------------------504--------------------------7----------------7
2661-------------------85 --------------------------5----------------5
...--------------------...---------------------------...----------------...
6999------------------- 20---------------------------1-----------------1
9956-------------------50---------------------------5-----------------5
Unknown----------------(empty)---------------------(empty)-----------0
Grand Total------------ 2421------------------------11-----------------11


Grand Total “11“ is the amount of distinct projects +1 (because of the unknown member). So the last column shows the right amount of projects for the professor but I want Grand Total to sum those values and show, how many projects do the professors have (it should be „59“ if for all professors). How could I get the right value to be shown in Grand Total?

View 1 Replies View Related

Distinct Count With Null Values (grand Total)

May 10, 2007

Hello,

I am using SQL Server 2005. I have a DB of professors and information related with them. I created the cube, it consist of:
Measures:
Measure group Professors:
Amount of projects (COUNT proj_id)
Amount of publications (COUNT pub_id)
Amount of e_books (COUNT book_id)
--------------
Measure group Projects:
Distinct amount of projects (DISTINCT COUNT proj_id)
--------------
Measure group Publications:
Distinct amount of publications (DISTINCT COUNT pub_id)
--------------
Measure group E_books:
Distinct amount of e_books (DISTINCT COUNT book_id)
Calculated measures:
Amnt_Projects
iif ([Measures].[ Amount of projects ] = 0 OR [Measures].[ Amount of projects] = NULL,0,[Measures].[ Distinct amount of projects])
Amnt_Publications
(similar to the above one)
Amnt_E_books
(similar to the above one)
---------------------------
Dimensions:
dimPROFESSORS
- prof_id
-surname
-name
-gender
dimPROJECTS
- proj_id
-type name
-name
dimPUBLICATIONS
- pub_id
-type name
-name
dimE_BOOKS
- book_id
-name
Date_Projects
-date_id
-years
Date_Publications
-date_id
-years
Date_E_books
-date_id
-years


For example, when I browse the cube:
prof_id____Amount of projects___Distinct amount of projects___Amnt_Projects
1032------------------- 30 --------------------------1----------------1
1070-------------------90 --------------------------2----------------2
1111-------------------0 ---------------------------1----------------0
1137-------------------0 ---------------------------1----------------0
1234-------------------1404--------------------------9----------------9
1721-------------------504--------------------------7----------------7
2661-------------------85 --------------------------5----------------5
...--------------------...---------------------------...----------------...
6999------------------- 20---------------------------1-----------------1
9956-------------------50---------------------------5-----------------5
Unknown----------------(empty)---------------------(empty)-----------0
Grand Total------------ 2421------------------------11-----------------11


Grand Total “11“ is the amount of distinct projects +1 (because of the unknown member). So the last column shows the right amount of projects for the professor but I want Grand Total to sum those values and show, how many projects do the professors have (it should be „59“ if for all professors). How could I get the right value to be shown in Grand Total?

View 2 Replies View Related

T-SQL (SS2K8) :: How To Group Total Count Of Similar Items

Mar 30, 2015

We sell & ship packages that contain multiple items within them. The actual package (we call it the "parent item") is in the same table as the items within it ("child items"). If the record is a child item within a package, its "ParentId" field will contain the ItemId of the package.

So some sample records of a complete package would look like this:

ItemId | ParentId | Name | QtyAvailable
----------------------------------------
1 | NULL | Package A | 10
2 | 1 | Item 1 | 2
3 | 1 | Item 2 | 3

ItemId's 2 & 3 are items contained within the ItemId 1 package.

Now however, the client wants us to build a report showing all packages (all items where ParentId is NULL) however, they want to see the QtyAvailable of not only the package but the items as well (a total of 15 when using the example above), all grouped into a single line. So a sample report line would look like this:

Name | Available Qty
--------------------------
Package A | 15
Package B | 100

How can I do a SELECT statement that SUMS the "QtyAvailable" of both the parent & child items and displays them along with the package name?

View 6 Replies View Related







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