Aggregate (SUM) A Column And Then Use The Result?

May 7, 2007

Hi,



I am importing some data from Excel. I have to SUM one of the columns, and then use the result of the sum to calculate the percentages of each row. How can I use the Aggregate to give me a total of a column, so that i can use the total in another task and use formulas to calculate the percentages? i have tried to use multicast and join, but I get an extra row with the sum, which is not what I want; I want to use the sum for all the data.



Thanks

View 9 Replies


ADVERTISEMENT

Aggregate Function For Select Statement Result?

Oct 19, 2004

Ok, for a bunch of cleanup that i am doing with one of my Portal Modules, i need to do some pretty wikid conversions from multi-view/stored procedure calls and put them in less spid calls.

currently, we have a web graph that is hitting the sql server some 60+ times with data queries, and lets just say, thats not good. so far i have every bit of data that i need in a pretty complex sql call, now there is only one thing left to do.

Problem:
i need to call an aggregate count on the results of another aggregate function (sum) with a group by.

*ex: select count(select sum(Sales) from ActSales Group by SalesDate) from ActSales


This is seriously hurting me, because from everything i have tried, i keep getting an error at the second select in that statement. is there anotherway without using views or stored procedures to do this? i want to imbed this into my mega sql statement so i am only hitting the server up with one spid.

thanks,
Tom Anderson
Software Engineer
Custom Business Solutions

View 3 Replies View Related

Aggregating Values That Match Aggregate Result

Sep 23, 2015

The actual schema I'm working against is proprietary and also adds more complication to the problem I'm trying to solve. So to solve this problem, I created a mock schema that is hopefully representative. See below for the mock schema, test data, my initial attempts at the query and the expected results.

-- greatly simplified schema that makes as much sense as the real schema
CREATE TABLE main (keyvalue INT NOT NULL PRIMARY KEY, otherdata VARCHAR(10));
CREATE TABLE dates (datekeyvalue INT NOT NULL, keyvalue INT NOT NULL, datevalue DATE NULL, PRIMARY KEY(datekeyvalue, keyvalue));
CREATE TABLE payments (datekeyvalue INT NOT NULL, keyvalue INT NOT NULL, paymentvalue INT NULL, PRIMARY KEY(datekeyvalue, keyvalue));

[Code] ....

Desired results:

SELECT 1 AS keyvalue, 'first row' AS otherdata, '2015-09-25' AS nextdate, 30 AS next_payment
UNION ALL
SELECT 2, 'second row', '2015-10-11', 150
UNION ALL
SELECT 3, 'third row', NULL, NULL

I know I'm doing something wrong in the last query and I believe another sub-query is needed?

Let me answer a few questions in advance:

Q: This schema looks horrible!
A: You don't know the half of it. I cleaned it up considerably for this question.

Q: Why is this schema designed like this?
A: Because it's a 3rd-party mainframe file dump being passed off as a relational database. And, no, I can't change it.

Q: I hope this isn't a frequently-run query against a large, high-activity database in which performance is mission-critical.
A: Yes, it is, and I left out the part where both the date and the amount are actually characters and have to pass through TRY_CONVERT (because I know how to do that part).

View 2 Replies View Related

Converting Result Of Aggregate Function Calculation To A Double (C#)

Jan 5, 2008

I've put a SelectCommand with an aggregate function calculation and AS into a SqlDataSource and was able to display the result of the calculation in an asp:BoundField in a GridView; there was an expression after the AS (not sure what to call it) and that expression apparently took the calculation to the GridView (so far so good).
 If I write the same SELECT statement in a C# code behind file, is there a way to take the aggregate function calculation and put it into a double variable?  Possibly, is the expression after an AS something
that I can manipulate into a double variable?  My end goal is to insert the result of the calculation into a database.
What I have so far with the SelectCommand, the SqlDataSource and the GridView is shown below in case this helps:
  <asp:GridView class="gridview" ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="lbsgalDataSource">
<Columns>
<asp:BoundField DataField="Formulation" HeaderText="Formulation" SortExpression="Formulation" />
<asp:BoundField DataField="lbs" HeaderText="lbs" SortExpression="lbs" />
<asp:BoundField DataField="gal" HeaderText="gallons" SortExpression="gal" />
<asp:BoundField DataField="density" HeaderText="density" SortExpression="density" />

</Columns>
</asp:GridView>

<asp:SqlDataSource ID="lbsgalDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT
a.Formulation,
SUM (a.lbs) AS lbs,
SUM ((a.lbs)/(b.density)) AS gal,
( ( SUM (a.lbs) ) / ( SUM ((a.lbs)/(b.density)) ) ) AS density
FROM Formulations a INNER JOIN Materials b
ON a.Material=b.Material WHERE Formulation=@Formulation GROUP BY Formulation">

<selectparameters>
<asp:controlparameter controlid="DropDownList1" name="Formulation" propertyname="SelectedValue" type="String" />
</selectparameters>

</asp:SqlDataSource> 
 

View 2 Replies View Related

How To Aggregate A Column That Was Itself An Aggregate

Jul 15, 2005

I have a column that has an expression with a runningvalue in it, a "Carrying Cost" for each month. I need to create another column that aggregates the monthly Cost. I can't to do a Runningvalue on the Runingvalue. I can't even do a Sum on the Runningvalue.

View 9 Replies View Related

Query To Find A Value In Column B Based On An Aggregate Function On Column A?

Jul 20, 2005

Hi,Suppose I have a table containing monthly sales figures from my shopbranches:Branch Month Sales-----------------------London Jan 5000London Feb 4500London Mar 5200Cardiff Jan 2900Cardiff Feb 4100Cardiff Mar 3500The question I am trying to ask is this: in which month did each branchachieve its highest sales? So I want a result set something like this:Branch Month----------------London MarCardiff FebI can do a "SELECT Branch, MAX(Sales) FROM MonthlySales GROUP BY Branch" totell me what the highest monthly sales figure was, but I just can't figureout how to write a query to tell me which month corresponded to MAX(Sales).Ideas anyone?Cheers,....Andy

View 5 Replies View Related

How To Aggregate A Column By Concatenation

Mar 28, 2012

How do I aggregate a column by concatenation?

/*
SQL Server 2000 datbase

I have 3 tables.
A "client" table.
A "call history" table.
And a "call detail" table.

The "client" table contains data about individual clients.
The "call history" table contains data about calls to or from the clients in the "client" table. (This is a one-to-many relationship of client-to-history interactions.)
The "call detail" table contains detail data about a particular "call history" entry. (This is also a one-to-many relationship of history-to-detail entries.)
*/

Code:

DECLARE @Client TABLE (ClientID INT PRIMARY KEY, ClientName VARCHAR(100))
INSERT INTO @Client
SELECT 1 [ClientID], 'Client A' [ClientName]
UNION ALL SELECT 2, 'Client B'
UNION ALL SELECT 3, 'Client C'
UNION ALL SELECT 4, 'Client D'
SELECT c.ClientID, c.ClientName

[Code]....

View 5 Replies View Related

Aggregate Bitwise OR On A Column

Oct 22, 2014

I am trying to get a culmulative Bitwise OR operation on a column by query - rather than using a CLR function.

The problem is shown below:

CREATE TABLE #Operations (
PK INT NOT NULL IDENTITY(1,1),
UserName VARCHAR(50) NOT NULL,
UserProcess VARCHAR(50) NOT NULL,
ServerOperation VARCHAR(50) NOT NULL,
Permission INT NOT NULL );

[Code] ....

So Far I've tried SUM - wrong results, and STUFF - which doesn't seem appropriate for bitwise operation - neither give useful results.

-- SUM Operation - fails
SELECT DISTINCT
UserName,
ServerOperation,
SUM(Permission) AS Permission
FROM #Operations

[Code] ....

It may be possible to materialise the permissions each time one is changed (e.g. by to use a cursor ), however I would prefer a query or function or combination to generate the result.

View 5 Replies View Related

Selecting The Corresponding Column Value When Using Min Or Max Aggregate.

May 4, 2007

Greetings,

I have a dataset something like this:



Loc Value Time
A 3 1AM
A 8 2AM
A 2 3AM
A 1 4AM
...
B 8 1AM
B 1 2AM
...

When we collapse the Loc group I want to show the Max vlaue and the time it
occurred.



A 8 2AM
B 8 1AM



What is the expression for the Time column of the table to ensure
the time of the maximum value is shown?

Thanks

View 8 Replies View Related

SQL Server 2008 :: Display A Column Alias As Part Of The Result Set Column Labels?

Feb 26, 2015

Is there a way to display a column alias as part of the result set column labels?

View 9 Replies View Related

Aggregate Column Comparison In Sql Server Sql ?

Jul 27, 2005

I am no expert in sql, but I keep stubbling on this problem:I have a table t1 with 2 columns (a,b)I have a table t2 with 2 columns (c,d)I need to delete all records from t1 which have the same value (a,b)than the value of (c,d) in all records in the t2 table.I oracle, this is simple:delete from t1where (a,b) in (select c,d from t2)because Oracle has support for this syntax. Dont remember how they callit. But this is not support in sql server. So I have to resort to:delete from t1where a + '+' + b in ( select c + '+' + d from t2)Of course, a,b,c,d must be varchar for this to work. Basically I fake aunique key for the records. Is there a better way to do this?Thanks

View 3 Replies View Related

How To Get Aggregate Column From Joined Table

Feb 6, 2008

Can someone please help me with a better way to format the following query. This works, but I know it is hidious.






Code Snippet

select

convert(varchar, processed, 101) as Date,
count(o.id) as [# Orders],
sum(distinct a.runnercount) as [# Runners],
sum(o.total) as [$ Gross],
sum(o.fee) as [$ Fees],
(sum(o.total)-sum(o.fee)) as [$ Net]

from [order] o join (select convert(varchar,processed,101) as date, count(*) as runnercount from orderitem oi inner join [order] o on o.id = oi.orderid where typeofextraid = 4 group by convert(varchar,processed,101)) a on convert(varchar,processed,101) = a.date

where statemented = @statemented
group by convert(varchar, processed, 101)
2 tables: Order and OrderItem. I need the sum of a specific record type from the OrderItem table along with all the other aggregate columns group by day.

Thanks.

Nathan

View 1 Replies View Related

Error: Column Name X Appears More Than Once In The Result Column List.

Oct 3, 2006

Hello,I am trying to follow along with the Data Access tutorial under the the "Learn->Videos" section of this website, however I am running into an error when I try to use the "Edit -> Update" function of the Details View form: I'll post the error below.  Any clues on how to fix this?  Thanks in advance!!! ~DerrickColumn name 'Assigned_To' appears more than once in the result column list. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Column name 'Assigned_To' appears more than once in the result column list.Source Error: Line 1444: }
Line 1445: try {
Line 1446: int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery();
Line 1447: return returnValue;
Line 1448: }

View 3 Replies View Related

T-SQL (SS2K8) :: Create Sequential Aggregate Of A Column Using Sum?

Aug 17, 2015

create a sequential aggregate of a column using sum in tsql.

I want a column that will sum up all hours work by transaction date.

for example

Monday my hours work will be 8 and therefore my total transaction hours will be 8.

Tuesday my hours work will be 8 but I want the total hours of my total transaction hours to 16.

Wed my total hours work will be 5 and I want the total hours of my total transaction hours to 21. etc.

Select myname, weekday, hours worked, Totalhours_ToDate =Sum(hours worked) from table

View 5 Replies View Related

Transact SQL :: Create Sequential Aggregate Of A Column Using Sum?

Aug 17, 2015

I need to create a sequential aggregate of a column using sum in tsql.

I want a column that will sum up all hours work by transaction date.

for example

Monday my hours work will be 8 and therefore my total transaction hours will be 8.

Tuesday my hours work will be 8 but I want the total hours of my total transaction hours to  16.

Wed my total hours work will be 5 and I want the total hours of my total transaction hours to  21. etc.

Select myname, weekday, hours worked, Totalhours_ToDate =Sum(hours worked)from table

View 3 Replies View Related

Sending Column Name As A Parameter To Aggregate Function

Jul 29, 2006

How can do this. Because my stored function contains same clause except colums name.So I want to use column name as a parameter but how can send column name and use it like Sum(parameter) function .

my procedure like this:

ALTER PROCEDURE [dbo].[ORNEK10]

@YIL VARCHAR(4),

@TEKLIF_TURU VARCHAR(255)

AS

BEGIN

DECLARE @N1 FLOAT

DECLARE @N2 FLOAT

SET @N1 = ( SELECT DEGERI FROM PARAMETRE WHERE PARAMETRE_ADI='N1')

SET @N2 = ( SELECT DEGERI FROM PARAMETRE WHERE PARAMETRE_ADI='N2')

SET NOCOUNT ON;

--I want to avoid using if statements for Sum() function

IF(@TEKLIF_TURU='BASKAN_TEKLIF')

SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA,

SUM(BASKAN_TEKLIF) AS YILI,

((100+@N1)*SUM(BASKAN_TEKLIF))/100 AS YIL1,

((100+@N1)*(100+@N2)*SUM(BASKAN_TEKLIF))/10000 AS YIL2

FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP

ORDER BY KOD1, KOD2, KOD3, KOD4

IF(@TEKLIF_TURU='ENCUMEN_TEKLIF')

SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA,

SUM(ENCUMEN_TEKLIF) AS YILI,

((100+@N1)*SUM(ENCUMEN_TEKLIF))/100 AS YIL1,

((100+@N1)*(100+@N2)*SUM(ENCUMEN_TEKLIF))/10000 AS YIL2

FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP

ORDER BY KOD1, KOD2, KOD3, KOD4



IF(@TEKLIF_TURU='MECLIS_TEKLIF')

SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA,

SUM(MECLIS_TEKLIF) AS YILI,

((100+@N1)*SUM(MECLIS_TEKLIF))/100 AS YIL1,

((100+@N1)*(100+@N2)*SUM(MECLIS_TEKLIF))/10000 AS YIL2

FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP

ORDER BY KOD1, KOD2, KOD3, KOD4

END

View 4 Replies View Related

SQL Server 2012 :: Updated Aggregate Column Where Value Is A Rolling Sum

Apr 29, 2014

I am trying to create an aggregate table where the value is a rolling sum. Type a on date 1 is the sum of the values in the main tbl. Type a on date 2 is the sum of values for type a on date 1 and date 2. Is this possible? I have been trying update t sql with sum(case where date <= date) statements but can't get it to run.

create table main_table (type nvarchar(10), date int, datavalues int);
insert into main_table
values('a', '1',3);
insert into main_table
values('b', '1',4)

[Code] .....

View 9 Replies View Related

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.

How can I get round to this?

View 6 Replies View Related

Cannot Find Either Column Dbo Or The User-defined Function Or Aggregate Dbo.FN_NIVELCOMPETENCIACARGO, Or The Name Is Ambiguo

May 4, 2006

Hello i have this query and I havent been able to solve it

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.FN_NIVELCOMPETENCIACARGO", or the name is ambiguous.

I have tried with dbo and withou dbo, specifyng columns inside it,



Thanks

select a.nmempresa,a.nmtipocompetencia, d.dsnombreciclo, c.dsnombrecargo,a.dstipocompetencia, a.dscatalogo,

b.popeso as PesoTipoCompetencia, f.dsnombrecompetencia as Competencia, e.pocompetencia as PesoCompetencia,

g.DSOPCIONESCALA, g.PESO

from

tgsc_tiposcompetencias a, TGSC_TIPOSCOMPETENCIASxcargo b, tgsc_cargos c, tgsc_ciclos d,

tgsc_competenciasxcargo e, tgsc_competencias f,

(select

dbo.FN_NIVELCOMPETENCIACARGO(a.nmempresa,a.nmciclo, a.nmtipocompetencia,c.nmcargo,f.nmcompetencia)) as g

where a.nmempresa=72 and a.nmciclo=9

and b.nmtipocompetencia=a.nmtipocompetencia

and b.nmcargo=10 and b.nmempresa=72 and b.nmciclo=9

and c.nmcargo=10 and c.nmempresa=72 and c.nmciclo=9 and d.nmciclo=9

and e.nmcargo=10 and e.nmciclo=9 and e.nmempresa=72

and f.nmcompetencia=e.nmcompetencia and f.nmtipocompetencia=a.nmtipocompetencia

and f.nmtipocompetencia=b.nmtipocompetencia

View 7 Replies View Related

SQL Server 2012 :: Column X Is Invalid In Select List Because It Is Not Contained In Aggregate Function

Apr 3, 2015

I have a specific variation on the standard 'Column Invalid' question: I have this query that works fine:

SELECT vd.Question ,
csq.Q# ,
csq.Q_Sort ,
csq.Q_SubSort ,
AVG(CAST(vd.Response AS FLOAT)) AS AvgC ,
vd.RType

[Code] ....

When I add this second average column like this:

SELECT vd.Question ,
csq.Q# ,
csq.Q_Sort ,
csq.Q_SubSort ,
AVG(CAST(vd.Response AS FLOAT)) AS AvgC ,

[Code] ....

I get the error: Column 'dbo.vwData.Response' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Clearly things are in the right place before the change, so I can only assume that the OVER clause is my problem. Is this just not possible?

View 1 Replies View Related

Cannot Perform An Aggregate Function On An Expression Containing An Aggregate Or A Subquery.

Oct 19, 2007

Can any1 tell me why i am getting an error


SELECT DISTINCT

--p.voucher,

--p.amount,

p.siteID,

b.siteID,

SUM((round(b.total,2,2)) - SUM(round(p.amount,2,2))) AS OutStandingBalance,

SUM((round(b.total,2,2)) - SUM(round(p.amount,2,2))) AS CashCheque,

SUM((round(b.total,2,2)) - SUM(round(p.amount,2,2))) AS Vouchers

FROM

BillingTotal b,

Payment p

--WHERE

-- s.sitename=@cmb1

--AND p.siteid = s.siteid

-- p.voucher = 0

-- p.voucher = 1

GROUP BY p.siteID,b.siteID



Msg 130, Level 15, State 1, Line 1

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

View 8 Replies View Related

Analysis :: Calculated Member From Aggregate And Non-aggregate Factors

Sep 22, 2015

I have 2 Dimensions in SSAS (see below end), I want to create a calculated member, named

This_Year_Billable_Objective_Count, with its formula = BillableLastYear*(100+ BillableObjective)/100.

The first factor,  BillableLastYear is a number, aggregated (sum) from child units.

The second factor,  BillableObjective is a percent number (for example 28 means 28%), it's not aggregate. It's an dependent value for each unit.

How can I calculate This_Year_Billable_Objective_Count for each unit?

\ able 1
SELECT [UnitKey]
      ,[UnitID]
      ,[UnitName]
      ,[Unit2Name]
      ,[Unit3Name]
      ,[Unit4Name]

[Code] .....

View 6 Replies View Related

Need Help On Getting Result From Row To Column

Jan 17, 2008

Hi
I need help to build the below data to my requirement
i have table having the following data's








NoofLive
Action
Sold
Ratio
EffDt

10-49
43
0
0
1/1/2008

50-99          
62
0
0
1/1/2008

100-199        
73
0
0
1/1/2008

200-299        
17
1
0.059
1/1/2008

300-499        
25
0
0
1/1/2008

500-999        
21
0
0
1/1/2008

1000+          
45
0
0
1/1/2008

100-199        
11
1
0.091
2/1/2008

1000+          
1
0
0
2/1/2008

100-199        
17
0
0
3/1/2008

500-999        
2
0
0
3/1/2008 
EffDt = (Jan-08,Feb-08,Mar-08)
I want creat result as follows from the above data's
















Jan-08
Feb-08
Mar-08

Eligible Lives
Quoted
Sold
Close Ratio
Quoted
Sold
Close Ratio
Quoted
Sold
Close Ratio

10 - 49
43
0
0
0
0
0
0
0
0

50 - 99
62
0
0
0
0
0
0
0
0

100 - 199
73
0
0
11
0
0
0
0
0

200 - 299
17
1
0.059
0
0
0
17
0
0

300 - 499
25
0
0
0
0
0
0
0
0

500 - 999
21
0
0
0
0
0
0
0
0

1000+
45
0
0
1
0
0
2
0
0
Please anybody can help build a query to generate the above result.
Thanks in advance
sthanika
 
 
 
 

View 1 Replies View Related

Add Apostrophe To Column In Result Set

Feb 5, 2004

I have a brain teaser for you all.

The end result: I need one of the columns in my result set (col2) to have a preceeding apostrophe (i.e., '001234 ).

The problem: I am building my query as a string and then using the EXEC() function to execute it. For example:
SET @strSQL = 'SELECT col1, col2 FROM mytable'
EXEC(@strSQL)

Just to tame any answers that might not be directed to the specific question, the query Must be built as a string and then executed.

I have been unable to obtain the solution and I am wondering if it is even possible?

TIA

View 3 Replies View Related

Column Name As The Result Of A Query?

Jan 11, 2005

Simple example would look like that in MS SQL

SELECT 'a' AS (SELECT language_name FROM language WHERE language_id = 1)

So that the display is

English
a

as we assume that

SELECT language_name FROM language WHERE language_id = 1

returns only English

I have tried to that with a variable but it does not work

declare @that as varchar(15);
set @that = (select language_name_u from language where language_id = 1);
select 'a' as @that

LOL

I just tried another way as i was going to post

declare @that as varchar(15);
set @that = (select language_name_u from language where language_id = 1);
select 'a' as "@that"

and it worked!

Posting anyway so people might answer with a better solution with no variable

Thanks a lot

Mordan

View 1 Replies View Related

How To Display Result Of Different Year In Different Column Instead Of Different Row?

Feb 7, 2006

I am trying to display component usage in January for the past year, if I want to display the year in different column, what should I do?
eg.
component_id   component_description   qty_used_on_2005_Jan   qty_used_on_2006_Jan
C58B0BDD       tape drive                             2                                              3
Currently I am using this sql:
select cast(year(date_complete) as varchar(10)) + ' Jan' as Year, component_id, component_description,sum(component_qty) as total_qty_used
from view_jobComponent
where month(date_complete) = 1group by component_id, component_description, cast(year(date_complete) as varchar(10)) + ' Jan'order by component_id, component_description
which I will get something like this:
Year          component_id   component_description   total_qty_used
2005 Jan    C58B0BDD       tape drive                             22006 Jan    C58B0BDD       tape drive                             3

View 9 Replies View Related

Dynamic Name Of Result Column In S-proc?

Oct 12, 2004

How can I make this stored procedure concept work:

-----------------------------------------------
Create Procedure MyProc @MyValue varchar(5)
As
Declare @ColumnName as varchar(11)
Set @ColumnName = 'Price_' + @MyValue
Select Sum(Price) As @ColumnName --????
From MyTable where Item = @MyValue
Return
-----------------------------------------------

Using @MyValue = 23 should make the Sum(Price) column name 'Price_23'. It's not working. What am I doing wrong?

Bjorn

View 2 Replies View Related

Stuck To Arrange Result In Column

Jun 8, 2008

Last query, mr. visakh help to produce a result as follow

Date_Taken | Main_ID | Daily_Rainfall
-------------------------------------------
5/1/2005 | 194 | 142
6/1/2005 | 194 | 155
7/1/2005 | 194 | 132
8/1/2005 | 194 | 199
5/1/2005 | 196 | 333
6/1/2005 | 196 | 544
7/1/2005 | 196 | 722
8/1/2005 | 196 | 845
...
...
*Combination of Date_Taken and Main_ID generate unique row
*Above data consist of 1 May 2005 to 1 AUG 2005 data (4 month data for each Main_ID), which is Date_Taken start from 1st day every month.
*Date_Taken | Main_ID | Daily_Rainfall
-------------------------------------------
5/1/2005 | 194 | 142
---> Mean, In May 2005 Main_ID=194 having 142 Daily_Rainfall
6/1/2005 | 196 | 544
---> Mean, In Jun 2005 Main_ID=196 having 544 Daily_Rainfall

Let's say, current month is 8
I stuck to do the query to display result like as follow

Date_Taken | Main_ID | CurrentMonth_DR | LastMonth_DR | Last2Month_DR| Last3Month_DR
--------------------------------------------------------------------------------------
8/1/2005 | 194 | 199 | 132 | 155 | 142
8/1/2005 | 196 | 845 | 722 | 544 | 333
...
...
*CurrentMonth_DR is 8/1/2005, LastMonth_DR is 7/1/2005, Last2Month_DR is 6/1/2005 and so on ( this can be harcoded in sql)

Plz help me

View 1 Replies View Related

Ignore Column If Result Set Is Null

Jul 12, 2013

Is there a way to ignore a column/variable when the whole result set for the applied filter (where) is null?

Not all clients have data for every variable, i.e. some variables are client specific. There are too many variables and clients to amend the select query every time so I just want to ignore a col if its null.

I hope that makes sense (my inability to describe it might explain my inability to find anything related to it!)

The next step would be to run all clients' data in one go using, I believe, a cursor, but one step at a time!

View 7 Replies View Related

How To Insert Result Of Calculation In New Column

Jan 17, 2014

I have a clustered index in a table. this column is of datatype date. how can i retrieve the following?:

select [date], valueColumn from myTable
where [date] = '2000-01-03' and
('2000-01-03'+1) and
('2000-01-03'+2)

My Goal ist to retrieve 3 values of valueColumn of 3 subsequent days, calculate the average of this 3 values and insert this average in a third colum called [average3days].

View 12 Replies View Related

Rows Into Column Structure - How To Get Result Set

May 19, 2014

How to get the result set:

AwardNumber AwardDt AwardType_RSS AwardQty_RSS
A1 01/01/2004 RSS 100

QUERY:

create table structure(
AWARDNUMBER VARCHAR(10),
AWARDDT DATEtime,
AWARDTYPE CHAR(3),
QTYAWARDED DECIMAL(20,6)
)

insert into structure
select 'A1','1/1/2004',null,null
union all
select null,null,'RSS',100

current output:

AWARDNUMBERAWARDDT AWARDTYPEQTYAWARDED
NULL NULL RSS 100.000000
A1 2004-01-01 00:00:00.000 NULL NULL

View 1 Replies View Related

Using IS NOT NULL On Column Result From Subquery

Sep 17, 2005

I have a query where one or more of the columns returned is a resultfrom a subquery. These columns get their own alias. I want to filterout the rows containing NULL from the subqueries but it just won'twork. When running columnAlias IS NOT NULL i just get the error"Invalid column name 'columnAlias'.This is the query:SELECT k.UserId, k.Lastname, k.Firstname,(SELECT kscr.answer FROM Results kscr WHERE kscr.UserID =k.UserID) AS myColumnAliasFROM Users kWHERE myColumnAlias IS NOT NULL)When running without the WHERE clause, I get the following results:UserId Lastname Firstname myColumnAlias113 Norman Ola jepps820 Karlsen Kjell830 Pens Jens juubidooWhat I want is to get rid of UserId=820. What am I doing wrong?

View 3 Replies View Related

Identity Column In Query Result

Jul 20, 2005

I am firing a query like:SELECT TaskName, StartDate FROMTasksWHERE StartDate >= '01-Aug-2003'Now the result comes as:TaskName StartDate--------------------------Task1 01-Aug-2003Task5 10-Oct-2003etc.Now what I want is this:Sl. No. TaskName StartDate----------------------------------1 Task1 01-Aug-20032 Task5 10-Oct-2003How do I get the Sl. No. field (it does not exist in the table).Can I do it?-surajit

View 11 Replies View Related







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