Aggregate Functions - Adding Extra Column With Another Field
Jun 13, 2014
I have a simple query like:
select max(PTR_DATE)
from MPR_portfolio_transactions
group by PTR_SYMBOL
and this is working fine, but if I add an extra column with another field like:
select max(PTR_DATE) , PTR_SHAREBALANCE
from MPR_portfolio_transactions
group by PTR_SYMBOL
Then I get an error message like:
Column 'MPR_portfolio_transactions.PTR_SHAREBALANCE' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I have a table that is used for employee evaluations. There are six questions that are scored either 1, 2, 3, 4, or 5. I want to tally the responses on a page, but I wonder if I can do it without 35 separate calls to the database (I also want to get the average response for each question). I know I can do "SELECT COUNT(intWorkQuality) AS Qual1 FROM dbo.Summer_Project_Req WHERE intWorkQuality = '1' " and then "SELECT COUNT(intWorkQuality) AS Qual2 FROM dbo.Summer_Project_Req WHERE intWorkQuality = '2' " and so on. But can I somehow do the aggregating at the page level, and just refer back to a datasource that uses a generic statement like "SELECT intWorkQuality, intDepend, intAnalyze, intWrite, intOral, intCompatibility FROM dbo.Summer_Project_Req"? If I can, I am not sure what type of control would be best to use or what syntax to use to write the code-behind. I would like the results to be displayed in a grid format. Thanks in advance for your help.
I'm doing a jsp with database using sql.. I'm trying to get the max of score group by name from this table: Table record id_no. . . .name. . . . .score . . 1 . . . . .Philip . . . . .10 . . 2 . . . . . Jane . . . . .12 . . 3 . . . . . John . . . . .15 . . 4 . . . . . Anna . . . . .11 . . 5 . . . . . Jane . . . . .16
I use the code: query = "select name,max(score) from record group by name"; resultset = stmt.executeQuery (query);
However, there is an error. It says, SQL Exception: Column not found
I've checked several tutorial sites and the codes there are the same command that I use. I've also tried using other aggregate functions like the sum, still the same error comes out..
I'm trying to migrate an app. from Access to SQL Server, and find that Transact-SQL does not support LAST/FIRST functions. Is there any alternative to these?
Below is the Access SQL statement:
SELECT Last(tblZoneNameString.Val) AS strZoneName, tblZoneNameString.TagIndex FROM tblZoneNameString GROUP BY tblZoneNameString.TagIndex HAVING (((tblZoneNameString.TagIndex)>0));
I have a database with the following tables: - programmer - software - studies(name, splace, cost, course) I would like to find out which school has the max. nr. of students, but my query - SELECT splace FROM studies HAVING count(name) = (SELECT max(count(name)) FROM studies) - doesn't works, becouse MSSQL doesn't supports nested aggregat functions. What should I do? Please help me, thanks in advance.
It's basically just cobbled together using the aggregate function and TVF in the StringUtilities sample as a starting point. Er, sorry MS, I forgot to change the namespace from Microsoft.Samples.SqlServer.
using System; using System.IO; using System.Data; using System.Data.Sql; using System.Data.SqlTypes; using System.Text; using System.Collections; using System.Collections.Generic; using Microsoft.SqlServer.Server;
public void Merge(IntersectBinary other) { if (other.bitset.Length > bitset.Length) { Array.Resize(ref bitset, other.bitset.Length); } for (int i = 0; i < bitset.Length; i++) { bitset[i] &= other.bitset[i]; } }
public SqlBinary Terminate() { return new SqlBinary(bitset); }
public void Read(BinaryReader r) { int i = r.ReadInt32(); bitset = r.ReadBytes(i); }
public void Write(BinaryWriter w) { w.Write(bitset.Length); w.Write(bitset); } }
public sealed class SplitBinaryCls { [SqlFunction(FillRowMethodName = "FillRow")] public static IEnumerable SplitBinary(SqlBinary argument) { List<Int16> r = new List<Int16>(); if (!argument.IsNull) { for (int i = 0; i < argument.Length; i++) { for (int j = 0; j < 8; j++) { if ((argument.Value[i] & Convert.ToByte(1 << j)) != 0) { r.Add(Convert.ToInt16(i*8+j)); } } } } return r; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")] public static void FillRow(Object obj, out Int16 stringElement) { stringElement = (Int16)obj; }
private SplitBinaryCls() { } } }
To install the compiled dll something like:
CREATE ASSEMBLY BinaryUtilities FROM 'C:...BinaryUtilitiesindebugBinaryUtilities.dll' WITH permission_set=Safe; GO
CREATE AGGREGATE UnionBinary(@input smallint) RETURNS varbinary(4096) EXTERNAL NAME [BinaryUtilities].[Microsoft.Samples.SqlServer.UnionBinary]; GO CREATE AGGREGATE IntersectBinary(@input smallint) RETURNS varbinary(4096) EXTERNAL NAME [BinaryUtilities].[Microsoft.Samples.SqlServer.IntersectBinary]; GO CREATE FUNCTION SplitBinary(@input varbinary(4096)) RETURNS TABLE(ix smallint) AS EXTERNAL NAME [BinaryUtilities].[Microsoft.Samples.SqlServer.SplitBinaryCls].[SplitBinary]; GO
Hi.Just as we have AVG(COLUMN_NAME) and MAX(COLUMN_NAME) how can I writemy own variation of a such a function. If I can appreciate how to dothis,then I hopefully I can write a MEDIAN(COLUMN_NAME) type function or amore general function like a 10% percentile function with syntax suchasPERCENTILE(COLUMN_NAME,25).Regards JC......
Hi allFirstly this my first time posting to technical groups - so anymistakes I apologise for in advance.I am trying to count records in several secondary tables for the samerun in a primary table. However, there might be no records in thesesecondary tables for the specific run. Hence the sql below returnsnulls.Select run, (select count(errors) from table2 where run = t1.run groupby run) as errors, (select count(user) as users from table3 where run =t1.run and user = active group by run, dd)from table1 t1(Please note the different group bys. )I do not want nulls to be returned but to be replaced with 0. I havetried the isnull function but this does not work. egSelect run, (select isNull(count(errors),0) from table2 where run =t1.run group by run) as errors, (select isNull(count(user),0) as usersfrom table3 where run = t1.run and user = active group by run, user)from table1 t1Nor will isnull work if I put it around the select clause.Any suggestions?Thanks for the help!
Do aggregate functions (sum, count, min, max) inherently cause tablelocks?More concretely, would the following query typically result in a tablelock?select sum(quantity) as totalfrom productsThanks,Scott
I have a complex statement that is used in a SELECT statement. Afterall my calculations I need to do an additional filter on the results.Can I use an alias anywhere or is the AS clause just for columndisplay purposes?Instead of:SELECT column1,column2,some_complex_statement_using_SUM_AVG_and_a_few_CAS E_statementsAS TotalFROM table_nameHAVINGsome_complex_statement_using_SUM_AVG_and_a_few_CAS E_statements[color=blue]> 1[/color]Can I have:SELECT column1,column2,some_complex_statement_using_SUM_AVG_and_a_few_CAS E_statementsAS TotalFROM table_nameHAVINGTotal > 1As I understand it, the HAVING clause is used for filtering AFTERaggregate functions are calculated so the alias SHOULD be available.
SELECT SUM(TOTAL) FROM MYTABLE WHERE DATEORIGINATED='11/11/07'
the above query will give me total for dateoriginated , but I am reading that dateoriginated value from another table and that table has multiple value of dateoriginated.
what I would like to do is to run above SQL aggregate functions query for two different dates at the same time and I would like to get total
(6th attempt to post this on the forum - problems with the forum?)
Hello
Assume that you have SQL Server 2005 Standard Edition installed but only the Database Services and you patched it with SP2. Now assume that you need to install all the other components like Notification Services and Reporting Services, what are the correct steps to follow?
I tried this once this failed miserably and ended up in completely having to uninstall SQL Server 2005 and completely reinstalling it. Luckily for me this was a demo machine.
Hi, need help in this statement here. I have three tables here, i.e. Sales, SalesItem, & SalesPmt. I want to display a grid that shows the Total Bill and Total Payment amounts. My try is like this: SELECT SalesNo, SUM(Price*Qty) AS TotalBill, SUM(Payment) AS TotalPayment FROM ... GROUP BY.... No syntax error or whatever found, but the result of the total amounts is incorrect. Say the data of the respective table below: SalesItem
No Qty Price
1 1 5.00
2 2 12.00
3 4 3.50 SalesPayment
No Amount
1 10.00
2 5.00 But the result I get from the above query is:
TotalBill TotalPayment
86.00 45.00 Total Bill should be 43.00 and Total Payment should be 15.00. Apparently the problem is due to the fact that I and querying on multiple tables. The correct total payment amount was multiplied by the number of rows of sales items (15.00 x 3), while the correct total bill amount was multiplied by the number of rows of sale payments (43.00 x 2). So, what is the better way of writing this query?
I'm probably just being thick but is there a way to use conditional statements within aggregate functions? I'm trying to do something along the lines of the following -
Code:
SELECT SUM( CASE WHEN Currency='GBP' THEN TotalAmountCharged ELSE TotalAmountCharged/1.45 ) as total from bookshop_orders where year(OrderDate) = 2004 and month(OrderDate) = 9
Howdy,I need to write an update query with multiple aggregate functions.Here is an example:UPDATE tSETt.a = ( select avg(f.q) from dbo.foo f where f.p = t.y ),t.b = ( select sum(f.q) from dbo.foo f where f.p = t.y )FROM dbo.test tBasically I need to get some aggregate statistics about the rows offoo and store them in rows of t. The above statement works fine...butnote how the two subSelect's have the exact same WHERE clause. Thisscreams at me to combine them...but how? I would like to havesomething like this in my query:SELECT avg(f.q), sum(f.q) FROM dbo.foo f WHERE f.p = 2...and somehow store the results in t.a and t.b. Is there any way todo this?Thanks before hand!
Hi, Apologies in advance if you get confused by reading this.... I am trying to create an additional step in the Create Wizard User Control that is provided by ASP.net. The additional step that I want to add will come after a user will create their username, password, email etc. The information which I want to save in the extra step are details such as firstname, lastname, address, height, weight etc. (I am creating an online weight management system for dieticians).When I run through the application, the username, password etc save perfectly to the database, but nothing happens with the other "personal information". There are no errors thrown so I don't know where the problem is coming from.I have included the code below as I have it:The code behind the Register.aspx file is as follows: <asp:SqlDataSource ID="InsertExtraInfo" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString1 %>" InsertCommand="INSERT INTO [aspnet_UserInformation] ([first_name], [surname], [address1], [address2], [city], [country], [number], [height], [weight]) VALUES (@txtFirstName, @txtSurname, @txtAddress1, @txtAddress2, @txtCity, @txtCountry, @txtNumber, @txtHeight, @txtWeight)" ProviderName="<%$ ConnectionStrings:ASPNETDBConnectionString1.ProviderName %>"> <InsertParameters> <asp:ControlParameter Name="txtFirstName" Type="String" ControlID="txtFirstName" PropertyName="Text" /> <asp:ControlParameter Name="txtSurname" Type="String" ControlID="txtSurname" PropertyName="Text" /> <asp:ControlParameter Name="txtAddress1" Type="String" ControlID="txtAddress1" PropertyName="Text" /> <asp:ControlParameter Name="txtAddress2" Type="String" ControlID="txtAddress2" PropertyName="Text" /> <asp:ControlParameter Name="txtCity" Type="String" ControlID="txtCity" PropertyName="Text" /> <asp:ControlParameter Name="txtCountry" Type="String" ControlID="txtCountry" PropertyName="Text" /> <asp:ControlParameter Name="txtNumber" Type="String" ControlID="txtNumber" PropertyName="Text" /> <asp:ControlParameter Name="txtHeight" Type="String" ControlID="txtHeight" PropertyName="Text" /> <asp:ControlParameter Name="txtWeight" Type="String" ControlID="txtWeight" PropertyName="Text" /> </InsertParameters> </asp:SqlDataSource> Then the code I have behind the Register.aspx.cs page is: protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) { TextBox UserName = (TextBox)CreateUserWizard1.FindControl("UserName"); SqlDataSource DataSource = (SqlDataSource)CreateUserWizard1.FindControl("InsertExtraInfo"); MembershipUser User = Membership.GetUser(UserName.Text); //object UserGUID = User.ProviderUserKey; DataSource.InsertParameters.Add("UserId", UserGUID.ToString()); DataSource.Insert(); } I know there is a problem with the code on the aspx.cs page but I cant figure it out. I need the username / password information to relate to the personal details information. I know I have to create a foreign key in the asp_UserInformation table that will link to the username in the asp_Membership (where all the username / password info is stored) Any help will do, I'm almost in tears here!!!The Spud
I am having trouble with a particular query that is beyond my scope of understanding.
Basically I need to pull sales records based on the following criteria:
I have CustomerID, InvoiceNumber, ContractEndDate, MobileNumber, etc..
Customers recontract their mobile phone plans through us, and we have a new sales record for each time they recontract.
For example, CustomerNumber 123 has recontracted 3 times..
once on 2006-01-01, then on 2007-02-12, and finally on 2008-02-15..
So they have a 12 month contract each time.. then come in to recontract it.
So.. a customer has a single Customer Detail record, but may have many sales records attached. And a customer may have several sales for the SAME mobile phone number.
Currently to pull ALL sales records for all customers, my query is this:
Code:
SELECT xxx.CustomerID AS xxx_CustomerID, xxx.Invoice AS xxx_Invoice, yyy.PhoneType AS yyy_PhoneType, yyy.PlanType AS yyy_PlanType, yyy.ContractEnds AS yyy_ContractEnds, yyy.MOB AS yyy_MobileNumber
FROM dbo.SaleControl xxx INNER JOIN dbo.SaleDetails yyy ON xxx.Invoice = yyy.Invoice
WHERE yyy.ContractEnds IS NOT NULL AND xxx.CustomerID IS NOT NULL
We want to get a list of customers that we can call to recontract, based on the ContractEnd field.
However, we want UNIQUE mobile phone numbers, with the LATEST ContrtactEnd date.
So, Customer 123 has 6 sales, for 2 unique Mobile numbers, the sql may be like:
Code:
SELECT MAX(yyy.ContractEnds) AS LatestCED, yyy.MOB FROM dbo.SaleControl xxx INNER JOIN dbo.SaleDetails yyy ON xxx.Invoice = yyy.Invoice WHERE xxx.CustomerID='123' GROUP BY yyy.MOB
Now, this works fine, and of course if i remove the WHERE clause, it collects all unique mobiles, with latest ContractEnd date for each, for all customers. (Customer 123 displays 2 mobile numbers, each with the LATEST ContractEnd date)
BUT i need this information ALONG WITH the other fields (xxx.CustomerID, xxx.Invoice, yyy.PhoneType, yyy.PlanType) and i have tried a few ways of doing it, but can't get my head around it..
Keep getting errors about Aggregate functions and Group By clause, and i understand why i am getting them, just cant think of any alternative query.
Hi all!In a statement I want to find the IDENTITY-column value for a row thathas the smallest value. I have tried this, but for the result i alsowant to know the row_id for each. Can this be solved in a neat way,without using temporary tables?CREATE TABLE some_table(row_id INTEGERNOT NULLIDENTITY(1,1)PRIMARY KEY,row_value integer,row_name varchar(30))GO/* DROP TABLE some_table */insert into some_table (row_name, row_value) VALUES ('Alice', 0)insert into some_table (row_name, row_value) VALUES ('Alice', 1)insert into some_table (row_name, row_value) VALUES ('Alice', 2)insert into some_table (row_name, row_value) VALUES ('Alice', 3)insert into some_table (row_name, row_value) VALUES ('Bob', 2)insert into some_table (row_name, row_value) VALUES ('Bob', 3)insert into some_table (row_name, row_value) VALUES ('Bob', 5)insert into some_table (row_name, row_value) VALUES ('Celine', 4)insert into some_table (row_name, row_value) VALUES ('Celine', 5)insert into some_table (row_name, row_value) VALUES ('Celine', 6)select min(row_value), row_name from some_table group by row_name
How to write Aggregate functions for tables and lists as If I can write them many problems in my reports will be solved. I tried writng it in the filters but I got an error saying Aggregate functions are not allowed for tables and lists. Can any one help me in this regard?????
Hi, Assume there is no sale with over 2000 units, the first query returns no row while the latter returns 1 row with a null value. I am not questioning the result, I would like to understand conceptually what semantic difference between the Sql99 analytic function and regular aggregate function makes the result different in this case.
select sum(Quantity) over() from orderdetails where Quantity > 2000
select sum(Quantity) from orderdetails where Quantity > 2000
When I enter a data in a table, SQL Server automatically completes the data with blanks up to length of column. this happens in a web form also in Management Studiıo, Whan am I doing wrong ? does Collation have anything with it ? SQL Server 2005 / Developer Edition
I'm trying to add exernal functions defined by a third party in a dll. They developed the dll in Visual C++ and is provided as is, with very little additional info about the code. The dll is tested and can be integrated into an application developed with VB.NET but no other experiences are available. I tried to add the functions to SQL Server 2005 Express edition but on attempting to CREATE the ASSEMBLY i get the following error: CREATE ASSEMBLY for assembly 'ThirdPartyDll' failed because assembly 'ThirdPartyDll' is malformed or not a pure .NET assembly. Unverifiable PE Header/native stub. No rows affected. (0 row(s) returned) @RETURN_VALUE = -6 Finished running [dbo].[ThirdPartyDll].
Is there an alternative way to add these functions for non pure .NET assemblies, or in general, is there a workaround to solve the problem?
By the way, do i need to register the dll with RegSvr32 first?
I have worked with straight-forward simplistic SSIS up to now, so I apologize if this is a simple question. I have a SQL table destination that accepts daily data from an AS400 table. We now have a need to datestamp the incoming data so I added a new column to the destination table where I want today's date. Is there a data flow transformation that I need to use to default the destination column to today's date? Time is not a consideration and not needed, just the date.
Hi, I am declaring a table with 2 column Id, and Name. Id is a integer column but Name is a Varchar. I am declaring Name as VARCHAR(100) you can say that varchar(100) is more than enougf for a name column. But lets suppose ifn futuer user will enter data only till 100 characters but lets suppose i put or declare it as NAME VARCHAR(4000), That means a column requires only 100 memory space but i am giving 4000 to that column So in case of SQL any drwbacks are there for this approach. Meaning my 3900 space will not be used so will it a wrong thing or we can declare it as ,,, it will put no effect??? or what are the drawback??
I'm trying to make a report with the following layout:
Car Sales 2004 2005 Var % Total 10 20 50% Green 7 14 50% Red 3 6 50%
I'm using a matrix and the data is coming from a cube. One dimension called 'Years' is used to fill the matrix columns and the data corresponding to the car sales is filled by a measure called 'Sales'. I've built part of the example but I can't add the final column ( the VAR% column). If I try to add a static column in the end it apears only one year. The behavior that I would like to have is simillar to the situation when we add the Subtotal column. Although, instead the sum() made by subtotal I would like to calculate the variation percentage between years. Is there any way to add a final column into a matrix avoiding the problem that I'm having or maybe change the behavior of Subtotal column?
We have an Access application using Jet. I added some new indexes yesterday and now they are being blamed for poor Access application performance. I then dropped the new indexes. The poor performance continued until the Access application was re-linked to the SS2000 database. Then things returned to normal.
Question, does Access/Jet persist SqlServer schema info in its MDB (or elsewhere?) I am told that the MDB is copied from a share to the local PC where it grows during its use. Some people are saying the MDB persists schema info about the SS2000 schema which influences how Jet accesses the SS2000 database. Is that true? Is there a link where I can read about this? I am a dba and am not an Access developer . . .