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


ADVERTISEMENT

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

SQL Server 2012 :: Retrieving Minimum Value Over Rolling Time Range?

Apr 28, 2015

I need to provide a minimum value over a 12 hour time range of data. I'm struggling with performance issues due to the amount of data. Currently I log about 100 devices reporting once per minute into a table. Also about once per minute I need to pull the minimum value reported for each device in the last 12 hours. Currently I'm maintaining a separate table with entries for just the last 12 hours and just performing a Select Min(Temp) Where DeviceID=x, but it already holds about 700,000 records at any given time. The number of devices will increase substantially and this will no longer be viable.

Sample Table
ID DeviceID Temp InsertDate
1 10 55 04-28-2015 8:00 AM
2 65 74 04-28-2015 8:00 AM
3 44 23 04-28-2015 8:00 AM
4 10 87 04-28-2015 8:01 AM
5 65 65 04-28-2015 8:01 AM

View 3 Replies View Related

SQL Server 2012 :: Query - Counting Item Occurrence Over A Rolling 72 Hour Period

Jun 18, 2015

I am using MS SQL 2012 and have a pretty simple table dbo. Migration Breakdown with sample data as follows.

DepartDateTime ZoneMovement
2015-06-26 14:00:00.000 6 to 4
2015-06-26 14:00:00.000 11 to 7
2015-06-26 15:30:00.000 9 to 6
2015-06-26 21:00:00.000 7 to 3
2015-06-27 08:01:00.000 7 to 4

[code]....

What I am trying to do is parse the data set to find out when we have more than three like movements ex. 3 to 10 within ANY rolling 72 hour period. I have looked at the SQL Window Functions OVER with a ROW | RANGE subclause, but I can't find out how to tackle this rolling 72 hour business.

View 9 Replies View Related

SQL Server 2012 :: Using CTE To Aggregate Separate Tables?

Aug 20, 2014

I am trying to tie together tables that show quantities of a product committed to an order and quantities on hand by a location.

My end result should look like the below example.

Item Location QtyOnHandByLocation SumQtyCommitTotal
Prod1 NJ 10 10
Prod1 NY 10 0
Prod1 FL 0 0
Prod1 PA 0 0

So I can see I have 10 items in NJ On Hand and Committed to an order. 10 available in NY but not on an order. Then the other two locations have no quantities.

Below is the CTE but it produces inaccurate results. I've tried running it several different ways by playing with the grouping but have no luck thus far.

--create the temp table
Create table #SalesLine
(
Novarchar (50) not null
, LocationCodevarchar (50) not null
, QtyCommitint not null
)
create table #ItemLedgerEntry

[code]....

I am close to the desired results but can't find a way.

View 9 Replies View Related

SQL Server 2012 :: Last 30 Days Aggregate Query

Dec 1, 2014

I'm trying to write a query that returns last 30 days data and sums the amount by day. However I need to do it for every year not just the current one(I need to go back as far as 2000).

declare @t table (id int identity(1,1), dt datetime, amt MONEY)
insert into @t (dt, amt)
select '2014-11-30 23:39:35.717' as dt, 66 as amt UNION ALL
select '2014-11-30 23:29:16.747' as dt, 5 as amt UNION ALL
select '2014-11-22 23:25:33.780' as dt, 62 as amt UNION ALL

[Code] ....

--expected output
select '2014-11-30' AS dt, 71 AS Amt UNION ALL
select '2014-11-22' AS dt, 62 AS Amt UNION ALL
select '2014-11-20' AS dt, 66 AS Amt UNION ALL
select '2014-11-18' AS dt, 102 AS Amt UNION ALL

[Code] ....

View 8 Replies View Related

SQL Server 2012 :: Inserted / Updated Records Count For Logging?

Feb 13, 2015

Initially I had designed ETL using Dataflow task in SSIS , No I have converted into Store procedure using merge statement.

I am getting new records inserted, source records and deleted row count when I am running sqp manually.

In ssis simple I have used the rowcount transformation to capture the records.

below variable i have declared in SSIS Package.

User::etlArchiveLogId
User::sourcerecords
User::newrecords
User::changerecord

now I am incremental loading using Stored procedure below is the sp which is executing when task success and logs the records.

ALTER PROCEDURE [dbo].[usp_LogArchiveBBxEndTime]
@EtlArchiveLog_Id int,
@RowsSource int,
@RowsNew int,
@RowsChanged int,
@Sucessful bit,
@Description varchar(500)

[code]....

Now I want to log the variable records which I have declared in my stored procedure .how can I log it in table?

View 1 Replies View Related

SQL Server 2012 :: Trying To Add Third Grouping Set To Return Average Aggregate

Feb 16, 2014

i'm building a query to return metrics that will drive 3 seperate pivot tables showing

1. Total count of LineItems per D_Type each month
2. Total count of LineItems per Status each month
3. Avg count of LineItems per Invoice each month

I am able to get the first two, but having hard time with the 3rd.

Here's some representative ddl
create table Remediation
(Invoice nvarchar(10), D_Type nvarchar(20), Status nvarchar(20), RemediationDate datetime);

insert into Remediation values
--this will create data for Jan, 2014
('501', 'Recycle', 'Pass', getdate()-30),
('501', 'Reuse', 'Pass', getdate()-30),
('501', 'Remarket', 'Fail', getdate()-30),

[code]....

how to add the average metric to this query?

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

SQL Server 2012 :: Solve Null Value Is Eliminated By Aggregate Or Other SET Operation?

Nov 26, 2013

I execute the code below

declare @LastDate datetime
SELECT @LastDate = max([LastUpdate])
FROM [exhibitor].[dbo].[blgBelongs]
WHERE (([Table1]=@module1 OR [Table2]=@module2 )or ([Table2]=@module1 OR [Table1]=@module2 )
AND Exists (SELECT [Table1],[Table1ID] FROM [exhibitor].[dbo].[blgBelongs] WHERE table2=30 and table2ID=@dmn_ID))

Before I see @LastDate , I see this warning

Warning: Null value is eliminated by an aggregate or other SET operation.

View 7 Replies View Related

SQL Server 2012 :: Warning - Null Value Is Eliminated By Aggregate Or Other SET Operation

Apr 28, 2015

In a t-sql 2012 query that will be updated in a stored procedure I am getting the following warning message:

Warning: Null value is eliminated by an aggregate or other SET operation. I would like to get rid of this warning missing without just turning off the warning messages.

I would like to change the sql so that it does not occur. The following is my new sql that generates the warning:

case when (coalesce(a.status,ae.status) = 'A') and (IsNull(ae.excuse, 'U') = 'U') and (IsNull(ae.code, 'DRC') = 'DRC') then

sum(DATEDIFF(minute,pm.startTime,pm.endTime)-coalesce(pm.lunchTime,0)-coalesce(a.presentMinutes,0)) else 0 end as DRCMinutes,

The sql is part of a select statement.

View 1 Replies View Related

SQL Server 2012 :: Error Message - Aggregate Function And Group By Clause

Feb 19, 2014

I'm trying to write a query to select various columns from 3 tables. In the where clause I use a set of conditions, but most important condition is that I only want to see all results from the different columns where the ph.ProdHeaderDossierCode contains at least 25 lines of processed hours. I tried this with group by and having, but I constant get error messages on all other columns that I want to see: "is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause". How can I make this so I can see all information I need?

Here is my code so far:

selectph.CalculatedTotalTime,
ph.ProdHeaderDossierCode,
ph.MachGrpCode,
ph.EmpId,
pd.PartCode
fromdbo.T_ProcessedHour ph,

[Code] ....

View 8 Replies View Related

SQL 2012 :: Rolling Up Multiple Row And Columns Into A Single Cell NULL Error

Jul 28, 2015

So I have a problem with combining cells: some of the cells are blank and some of the cells have NULL value.

The combined blank cells return perfect.

But the combined cells in which 1 or more contains NULL will return as NULL

0-4139-00-01OPTIONAL EQUIPMENT 139 - A -
0-4139-00-02NVG EQUIPMENT 139 - A -
0-4139-00-03NVG EQUIPMENT 139 - A -
0139-01-01BRAKE RESERVOIR NULL

A part of the script which i use is:

STUFF((SELECT ', ' + i.ac_type + ' - '
+ i.range_or_single+ ' ' + ' - ' + i.serialno_to
FROM msc_item_effectivity i
inner JOINmsc_item h
ONb.taskcard_verno_i = h.taskcard_verno_i
WHERE h.itemno_i = i.itemno_i
FOR XML PATH('')), 1, 1, '')

i.ac_type = 139
i.range_or_single = A
i.serialno_to = blank or NULL

I want the result of the blank value to be the same as the NULL value.

0139-01-01BRAKE RESERVOIR 139 - A -

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

Updated Column Name

Feb 10, 2005

Hi,

Can anybody tell me how to find the column name(s) for recently updated table.

Thanks,

Kishore

View 6 Replies View Related

SQL Server 2012 :: Subtract / Exclude Value Items From A Column And Add It To Another Column In Same Table

May 26, 2014

I got a sales cost and cost amount table for my budget. the sales cost table is getting updated with FOBB items which makes the total incorrect . the FOBB values needs to be moved from the sales cost column to the cost amount column. how can i do it with an SQL script.

View 1 Replies View Related

SQL Server 2012 :: Format Value Of A Column And Insert It Into Another Column Of The Same Table?

Sep 18, 2014

A column of a table has values in the format - 35106;#Grandbouche-Cropp, Amy.

I need to format the column data in such a way that only the text after # (Grandbouche-Cropp, Amy) remain in the column.

The text before ;# (35106) should be inserted in to another column of the same table.

Below is the table structure:

create table [HR_DEV_DM].[CFQ_TEST].sp_CFQ_Commercial_Referrals
(
ID int identity,
PromotionalCode nvarchar(4000),
QuoteNumber nvarchar(100),
CreatedBy nvarchar(100),
Created datetime,
ModifiedBy nvarchar(100),
Modified datetime,
CreatedBy_SalesRepSharePointID int,
ModifiedBy_ModBySharePointID int
)

View 2 Replies View Related

Disallow A Specific Column's Value From Getting Updated

Jul 9, 2007

is there a way to do this in create/alter table without the overhead of a trigger? I want to ensure that one of the 'key' values (even though it may be duplicated) cannot change after it's been inserted.

View 4 Replies View Related

SQL 2012 :: Custom Bitwise OR Aggregate Function

Mar 18, 2014

I want to create a custom bitwise OR aggregate function.

I want to use it like the built in aggregate functions (MIN, MAX etc.)

SELECT dbo.bitwise_or(bit_string) FROM table

where bit_string is a nvarchar(3)

so for example if the table contains two rows ('100', '001') the above query should return '101'

I would like to implement this as a CLR function/assembly with the aggregate below:

CREATE AGGREGATE dbo.bitwise_or (bit_string nvarchar(3))
RETURNS [nvarchar(3)]
EXTERNAL NAME [Aggregate].[bitwise_or]

I have followed this post to implement amedian aggregate function [URL] ..... but there is a lot of code (not sure what is really needed in my case).

View 9 Replies View Related

SQL Server 2012 :: Group Column Based On Another Column

Jul 11, 2014

I have Table Like this

t_id w_id t_codew_name
358553680A1100EVM Method Project
358563680A1110EVM Method Project
358453684A1000Basic
358463684A1010Basic
358473685A1020Detail

[Code] ....

View 1 Replies View Related

Updating Modified/updated Date Column?

May 13, 2008

If your tables contain created and modified/updated dates what is the best practice for these?

1. Should you use UTC dates?
2. Do you use a default for the creation date (I assume yes)?
3. Should you create a trigger to handle the last update date? Or do you update the column directly in your stored procedures that modify data?

Also, as an aside if you store the user who created/updated the record do you store a foreign key reference to the user table or do you store the username as a varchar? Of course I know you'd normally store the fk, but I wasn't sure if the "logging" nature of the column suggests storing a string value.

View 2 Replies View Related

SQL 2012 :: How To Target Transactional Values With Aggregate Amount

Apr 27, 2015

I am trying to exclude records that have an assessed value that has been waived in an aggregation. For Example:

Here is my table:

CREATE TABLE #temptable (ReportingMonth Varchar(6), Fee_Code Varchar(20), Fee_Transaction_Amount Decimal(12,2), Fee_Transaction_Date Datetime, Fee_Transaction_Type Char)
INSERT INTO #temptable (ReportingMonth, Fee_Code, Fee_Transaction_Amount, Fee_Transaction_Date, Fee_Transaction_Type)
SELECT 'Jan-13', 'ONE TIME DRAFT FEE', '20', '01/24/2013', 'A'
UNION ALL SELECT 'Feb-13', 'LATE CHARGE', '33.6', '02/19/2013', 'A'
UNION ALL SELECT 'Mar-13', 'LATE CHARGE', '37.01', '03/18/2013', 'A'

[code]....

Here are Data Mapping Description

Reporting Month = Month - Year
Fee Code = Fee Description Name
Fee Transaction Amount = Fee Amount
Fee Transaction Date = When Fee Amount was Applied
Fee Transaction Type = "A" = Assessed Fee; "W" = Waived Fee; "P" = Paid Fee

I've also included an image with beginning data set and what I want to identify in red and what my final data set should look like after the exclusion of those 4 records are removed.

Here are the logic requirements:In the attachment what I need the logic to do is essentially identify the $20 One Time Draft Fee from the first instance using the MIN Transaction date. Since there were $80 waived for this fee code (One Time Draft Fee), I would expect to see the first 4 (highlighted in red) to be identified as the target and as you can see in the attachment the second data set had the 4 highlighted items removed. That should be my final output.

trying to loop and remove the waive amounts from the assess amounts and tied it back to remove from my base data.

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

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 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 2012 :: Update A Column Using Value Of Another Column

Sep 9, 2015

I have a student table like this studentid, schoolID, previousschoolid, gradelevel.

I would like to load this table every day from student system.

During the year, the student could change schoolid, whenever there is a change, I would put current records schoolid to the previous schoolid column, and set the schoolid as the newschoolid from student system.

My question in my merge statement something like below

Merge into student st
using (select * from InputStudent ins)
on st.id=ins.studentid

When matched then update

set st.schoolid=ins.schoolid
, st.previouschoolid= case when (st.schoolid<>ins.schoolid) then st.schoolid
else st.previouschoolid
end
, st.grade_level=ins.grade_level
;

My question is since schoolid is et at the first line of set statement, will the second line still catch what is the previous schoolid?

View 4 Replies View Related

Record Not Updated Or Deleted When Any Column Consists The Null Value

Oct 23, 2007

Hi All  In My application when i want to work with sqldatasource for updation and delteion tasks it is working properly when all the columns consists the data. If any of the column consists the null values its not updating and deleting. Advices are needed.Thank uBaba 

View 4 Replies View Related

Trigger Not Running When Trying To Select Data From A Column That Is Being Updated?

Dec 11, 2006

Trigger not running when trying to select data from a column that is being updated?

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

Rolling Back In SQL Server

Feb 19, 2004

One of our engineers here by mistake deleted some very important data without any begin trans block and we need the data back very badly.. We have not closed the session as of now.. The engineer was logged in as sa to the DB.

Can someone please help soon on urgent basis...

View 6 Replies View Related

Transact SQL :: How To Get Info Which Stored Procedure Updated A Column For Particular Timestamp

Jul 31, 2015

How to get the details of a stored proc or sql query which updated a particular table for specified time stamp or interval. Is there any query to get this?

View 3 Replies View Related







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