How to calculate a rolling average within SQL Server Compact

There are at least a dozen ways to skin this cat in regular SQL Server, but I am trying to solve this problem within the limitations of SQL CE. I have a table of stock values:
Stock, Date, Open, High, Low, Close
and I want to add 1 column "RollingAVG" which is simply the AVG(Close) over a specified timeframe (say 30 days)
This code here works in SQL Server 2012 just fine (of course) but I need something that produces the same results in SQL CE.  Any thoughts?  Thanks!
SELECT b.Symbol,b.DateTrade, b.ValueClose,
(SELECT
AVG(a.ValueClose)
FROM
HistoryPrice a
WHERE
a.DateTrade >= DATEADD(d,-30,b.DateTrade)
AND a.DateTrade <= b.DateTrade
AND a.Symbol = b.Symbol
) as Rolling30Close
(SELECT
MIN(a.ValueLow)
FROM
HistoryPrice a
WHERE
a.DateTrade >= DATEADD(d,-30,b.DateTrade)
AND a.DateTrade <= b.DateTrade
AND a.Symbol = b.Symbol
) as Min30Day
(SELECT
MAX(a.ValueHigh)
FROM
HistoryPrice a
WHERE
a.DateTrade >= DATEADD(d,-30,b.DateTrade)
AND a.DateTrade <= b.DateTrade
AND a.Symbol = b.Symbol
) as Max30Day
FROM
HistoryPrice b
order by Symbol,DateTrade desc
Shane

Hi,
AVG function is supported in SQL Server Compact. However, embedded select clause is not supported in Visual Studio and a SQL Execution error will be thrown out.
I suggest you optimize your query. You can refer to the below code:
AVG (SQL Server Compact)
http://technet.microsoft.com/en-us/library/ms174124.aspx
If you have any feedback on our support, please click here.
Thanks.
Tracy Cai
TechNet Community Support

Similar Messages

  • How to get Cumulative Update packages for SQL Server Compact v3.5 SP2 for use on a Windows Mobile device

    There are links on the pages for various Cummulative Updates for SQL Compact v3.5 SP2 which look to relate to the desktop version, but are these also available for Windows Mobile devices?  If so, what is the process to get hold of them?
    We are seeing intermittent problems with corrupted databases on devices which are using SQL Compact v3.5 SP2 and have seen that some of the Cumulative Updates do relate to corruption and would like to see if these can help to solve the issue.

    Just select the KB article, at the top of each there is a link to request a hotfix, you will then get a email with a download link. The 8088 and 8109 hotfixes also apply to Windows Mobile.
    http://erikej.blogspot.dk/2010/08/sql-server-compact-35-sp2-downloadable.html
    Please mark as answer, if this was it. Visit my SQL Server Compact blog http://erikej.blogspot.com

  • Rolling Averages in Sql Server 2008

    I dint get the perfect answer last time and i am still working on the exact output that i need.
    I have the two integer columns in my table and i have to calculate averages for those two columns.Hence my output should be 
    date col1 col2 AVGcol1 AVGcol2
    and the average of each row should be avg(value of current date and sum of last five date). In this case i have more than one row for a single date.That also needs to be considered.
    Thanks in Advance!!!!!!

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> I did not get the perfect answer last time and I am still working on the exact output that I need. <<
    Perhaps you might consider posting DDL and giving us sample date, so we can do your job for you?
    >> I have the two integer columns in my table and I have to calculate averages for those two columns. Hence my output should be 
    something_date, col1, col2, col1_avg, col2_avg
    and the average of each row should be avg(value of current date and sum of last five dates). In this case I have more than one row for a single date. That also needs to be considered.<<
    I might have guessed that the generic date was the key, but your narrative says this is not so. Too bad we have no idea what the key might be. Too bad we have no idea about NULLs, either! Why did we have to almost torture you to get anything? Just give us DDL
    at the start. 
    CREATE TABLE Garbage 
    (posting_date DATE NOT NULL, 
     col_1 INTEGER NOT NULL, 
     col_2 INTEGER NOT NULL, 
     PRIMARY KEY (???));
    INSERT INTO Garbage 
    VALUES
    ('2014-12-10', 250, 200), 
    ('2014-12-21', 100, 100), 
    ('2014-12-21', 150, 300), 
    ('2014-12-21', 100, 100), 
    ('2014-12-22', 150, 300), 
    ('2014-12-23', 100, 100), 
    ('2014-12-23', 150, 300), 
    ('2014-12-24', 100, 100), 
    ('2014-12-24', 150, 300), 
    ('2014-12-25', 200, 450); 
    Here is my guess: sum up each day's postings into G2. Now t34eh date could be a key! Then use G2 with a windows clause to get the prior 5 rows. That is not quite the same as the prior five
    days, however, if we have gaps. The RANGE option does not work completely in T-SQL, but we could do an outer join to a calendar table and some other tricks.
    WITH G2(posting_date, col_1, col_2)
    AS
    (SELECT posting_date, SUM(col_1), SUM(col_2) 
     FROM Garbage
    GROUP BY posting_date)
    SELECT posting_date, 
     col_1,
     AVG(col_1 * 1.00)
     OVER (ORDER BY posting_date 
     ROWS BETWEEN 5 PRECEDING AND CURRENT ROW)
     AS col1_avg, 
     col_2,
    AVG(col_2 * 1.00)
     OVER (ORDER BY posting_date 
     ROWS BETWEEN 5 PRECEDING AND CURRENT ROW)
     AS col2_avg
     FROM G2; 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Errors when Creating Aggregate Tables in OBIEE 11.1.1.6 within SQL server

    Hi All,
    I was trying to create an aggregate table in OBIEE 11.1.1.6 within SQL Server. The sql was generated successfully as below. But an error occurred when I use NQCMD to execute the sql and the following error showed:
    1. SQL for creating Aggregate Table:
    create aggregates
    "ag_Measure"
    for "ASOBI_DTT_Demo"."Measure"("ValidVIPCnt")
    at levels ("ASOBI_DTT_Demo"."日期"."月", "ASOBI_DTT_Demo"."門市品牌"."門市品牌", "ASOBI_DTT_Demo"."門市類別"."門市類別", "ASOBI_DTT_Demo"."內創門市"."內創門市", "ASOBI_DTT_Demo"."門市/倉庫"."門市/倉庫", "ASOBI_DTT_Demo"."門市群組"."門市群組", "ASOBI_DTT_Demo"."門市行政區課"."行政區", "ASOBI_DTT_Demo"."門市地區"."城市")
    using connection pool "ASOBI_DTT_Demo"."ASOBI_System10"
    in "ASOBI_DTT_Demo"."ASOBI"."dbo";
    2. Error Message:
    "ag_Measure"
    for "ASOBI_DTT_Demo"."Measure"("ValidVIPCnt")
    at levels ("ASOBI_DTT_Demo"."日期"."月", "ASOBI_DTT_Demo"."門市品牌"."門市品牌"
    , "ASOBI_DTT_Demo"."門市類別"."門市類別", "ASOBI_DTT_Demo"."內創門市"."內創門市"
    , "ASOBI_DTT_Demo"."門市/倉庫"."門市/倉庫", "ASOBI_DTT_Demo"."門市群組"."門市群
    組", "ASOBI_DTT_Demo"."門市行政區課"."行政區", "ASOBI_DTT_Demo"."門市地區"."城市
    using connection pool "ASOBI_DTT_Demo"."ASOBI_System10"
    in "ASOBI_DTT_Demo"."ASOBI"."dbo"
    [343][State: 37000] [Microsoft][SQL Server Native Client 10.0][SQL Server]CREATE
    、DROP or ALTER 陳述式中使用未知的物件類型 'aggregates'。
    Statement execute failed
    Which means "Using unknown object type 'aggregates' in CREATE. DROP or ALTER statements" in English.
    Can anyone give me a suggestion for this error?? Many thanks!!!

    Hi Martin,
    I guess, I was not clear enough. Let me try again
    How Aggregate Persistence works in OBIEE?
    Once you are done choosing options in the Aggregate Persistence wizard, it generates an intelligent Query.
    What query is it?
    If you happen to understand the query, it is not like any ANSI standard SQL (I would say DDL) query. As you might have noticed there are no SQL Server datatypes, lengths, keys, constraints etc. This query can only be understood by the BI Server.
    How do I issue this query?
    Since the logical query could only be understood by BI Server, it has to be issued only to BI Server Engine using some tool viz NQCMD in this case.
    What does issuing this query using NQCMD do?
    The execution steps are as follows, the moment the query is issue via NQCMD
    Aggregate Persistent Wiz Generate Query ----- Issued to ---> NQCMD ----- Passes the logical query to ---> BI Server ----- Parses the query ---> Builds the corresponding physical DDL statements Issued --->To the Database --- If successful ---> .RPD is automatically updated with the aggregated sources etc.
    How do I pass the query to BI Server using NQCMD?
    The format of issuing this logical query to BI Server using NQCMD is
    nqcmd -d <Data Source Name> -u <Analytics UserId> -p <Password> -s <command> > output.log
    where
    <Data Source Name> : Is the DSN name which OBIPS uses to talk to Oracle BI Server. Yes, it's the very same DSN that can be found in InstanceConfig.xml
    <Analytics UserID> : Any user in obiee with admin privileges.
    <Password> : Password of the obiee UserId
    <Command> : Logical SQL Command which you already have handy.
    Hope I was good this time..
    Dhar

  • How to delete number (00) in a SQL Server column ?

    how to delete number (00) in a SQL Server column ?
    example :
    column :        Births       before                     Births 
        after                          
                       199900                            
            1999
                       198200                               
         1982
                       200400                               
        2004
    help query

    You use REPLACE function to selectively replace text inside a string in SQL Server. The REPLACE function is easy to use and very handy with an UPDATE statement.
    SELECT Replace(births, '00', '')
    or
    update .....
    Also you can use STUFF()
    This function can be used for delete a certain length of the string and insert a new string in the deleted place.
    Select STUFF ('199900', 5, 2, '')
    --result 1900,1982,....
    Ahsan Kabir Please remember to click Mark as Answer and Vote as Helpful on posts that help you. This can be beneficial to other community members reading the thread. http://www.aktechforum.blogspot.com/

  • How to create user defined metrics for SQL Server target?

    The customer is not able to create a user defined metrics for SQL Server target.
    This is very important for him to use this product.
    He is asking how to create user defined metrics?
    I sent him Note 304952.1 How to Create a User-Defined SQL Metric in EM 10g Grid Control
    But it would work for an Oracle DB, but his target is SQL Server DB
    Not able to find the "User-Defined Metrics" link from Database home page.
    How to create user defined metrics for SQL Server target?

    http://download-uk.oracle.com/docs/cd/B14099_19/manage.1012/b16241/Monitoring.htm

  • How to use open Row set in sql server 2014

    Hello All,
    How to open the row set using sql server 2014 using link server connection.

    Hi  denyy,
    Are you referring to the OPENROWSET function in SQL Server 2014?
    The OPENROWSET method is an alternative to accessing tables in a linked server and is a one-time, ad hoc method of connecting and accessing remote data by using OLE DB. The examples below demonstrate how to use the OPENROWSET function:
    A. Using OPENROWSET with SELECT and the SQL Server Native Client OLE DB Provider
    SELECT a.*
    FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
    'SELECT GroupName, Name, DepartmentID
    FROM AdventureWorks2012.HumanResources.Department
    ORDER BY GroupName, Name') AS a;
    B. Using the Microsoft OLE DB Provider for Jet
    SELECT CustomerID, CompanyName
    FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'C:\Program Files\Microsoft Office\OFFICE11\SAMPLES\Northwind.mdb';
    'admin';'',Customers);
    GO
    C. Using OPENROWSET to bulk insert file data into a varbinary(max) column
    USE AdventureWorks2012;
    GO
    CREATE TABLE myTable(FileName nvarchar(60),
    FileType nvarchar(60), Document varbinary(max));
    GO
    INSERT INTO myTable(FileName, FileType, Document)
    SELECT 'Text1.txt' AS FileName,
    '.txt' AS FileType,
    * FROM OPENROWSET(BULK N'C:\Text1.txt', SINGLE_BLOB) AS Document;
    GO
    D. Using the OPENROWSET BULK provider with a format file to retrieve rows from a text file
    SELECT a.* FROM OPENROWSET( BULK 'c:\test\values.txt',
    FORMATFILE = 'c:\test\values.fmt') AS a;
    Reference:
    OPENROWSET (Transact-SQL)
    Using the OPENROWSET function in SQL Server
    Thanks,
    Lydia Zhang
    If you have any feedback on our support, please click
    here.

  • How to insert data from access to sql server ?

    How to insert data from access to sql server ?
    Please help me
    thanks

    phamtrungkien wrote:
    How to insert data from access to sql server by JAVA?The first four words of my last post:
    masijade wrote:
    JDBC with two connectionsGet a resultset from the jdbc-odbc bridge access connection, cycle through it and add batch insert commands to the jdbc connection to sql server. Give it a try and if the code has an error, then post your code ans ask a question.
    The real question, though, is why you think it absolutely necessary to use Java for this.

  • How to deploy a sql server compact 4.0 in windows xp?

    My program is developed by visual basic 6.0 with sql server compact 4.0.   How can I deploy it in windows xp sp3?
    Should I install .netframework version X in windows xp before sql server compact 4.0 ? 
    When I copy my program  to windows xp and run it , it shows not found provider error.

    I you use ADO, the OLEDB provider must be registered. To do the simply install the SQL Server Compact 4.0 SP1 runtime MSI
    Please mark as answer, if this was it. Visit my SQL Server Compact blog http://erikej.blogspot.com

  • How to restore the Password backup in sql server 2005

    How to restore the Password backup in sql server 2005

    Hello,
    THANKS............ BUT
    I executed this query 
    RESTORE DATABASE new_data1
    FROM DISK = 'd:\UK_DETAILS.bak'
    with password ='selfinity123'
    WITH MOVE 'UK_DETAILS.bak' TO 'D:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\new_data1.mdf',
    MOVE 'UK_DETAILS.bak' TO 'D:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\new_data1.ldf'
    I got the error 
    Msg 319, Level 15, State 1, Line 4
    Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.

  • How to call procedure in Java from SQL Server Database

    Hello Every Body
    i Have Question about
    How to call procedure in Java from SQL Server Database
    Thanks

    Hi,
    have you tried a Google search? I just gave it a 3 second try and already found: http://stackoverflow.com/questions/6113674/how-do-i-execute-a-ms-sql-server-stored-procedure-in-java-jsp-returning-table-d
    Frank

  • How do I make a connection to SQL Server Express using SQL Developer 1.5.3?

    How do I make a connection to SQL Server Express using SQL Developer 1.5.3, if it's possible at all?
    Also, I received a SQL Server dump file of some sort. Is there any way to read this file in SQL Developer and migrate the db to Oracle? Unfortunately I don't have raw DDL and DML for this database--just some sort of a binary dump file from SQL Server.
    Thanks.
    Dana

    Are you using SQL Developer 1.5.3 or 1.5.4?
    If using an older version (i.e. 1.5.3), then you'll have to add a DLL to your environment. This is [ntlauth.dll].
    If you don't find this DLL in your SQL Developer directory, then obtain the JDBC SQL SERVER Pluggin (jtds-1.2.2-dist.zip) from:
    http://sourceforge.net/project/showfiles.php?group_id=33291&package_id=25350
    Copy the ntlmauth.dll in the ...\\...\ide\lib directory (no need to register it).
    Note: this approach should work if using DQL Developer 1.5.3 and SQL Server Express 2008
    Regards,
    M. R.

  • How to convert rows to columns in sql server 2008

    How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)

    Lookup the Pivot transformation. From BOL:
    The Pivot transformation makes a normalized data set into a less normalized
    but more compact version by pivoting the input data on a column value. For
    example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
    details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
    single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
    null values.
    When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
    The column is passed through unchanged to the output. Because many input rows
    can result only in one output row, the transformation copies only the first
    input value for the column.
    The column acts as the key or part of the key that identifies a set of
    records.
    The column defines the pivot. The values in this column are associated with
    columns in the pivoted dataset.
    The column contains values that are placed in the columns that the pivot
    creates.
    Paul

  • How to find existing DAC connection to sql server

    How to find existing DAC connection in sql server  

    Hi RoyalM,
    Vishal has answered your initial question. If you have the connection issue. I suggest you elaborate the issue in a new thread.
    You can access DAC using SQLCMD from a command prompt. Or check the existing DAC connection in a command prompt:
    1. Open Command Prompt.
    2. Type: SQLCMD –S <servername\instance> -d master and press Enter.
    1> SELECT name,local_tcp_port FROM sys.dm_exec_connections ec join sys.endpoints e on (ec.endpoint_id=e.endpoint_id) WHERE e.name='Dedicated Admin Connection'
    2> go
    3. If it returns the result, it means there is an existing DAC connection. It also shows the port used by dedicated admin connection.
    Thanks.
    Tracy Cai
    TechNet Community Support

  • Can you tell me how I can put the data of sql server into SAP to auto gener

    Dear all,
             Can you tell me how I can put the data of sql server into SAP to auto generate PR?
    Best regards,
    Merry zhang

    Many thanks ,it is ok now.

Maybe you are looking for

  • I cant close itunes on my pc it keeps popping up

    when i close itunes it popps up again as if i started it again i tried reinstalling itunes a couple of times and tried troubleshooting it with some people but no one have never heard of the problem so i just dont know how to solve it out i can comple

  • One Wireless network, Multiple Airport Extremes

    What I would like to do is set up a single network SSID using lets say 4 Airport Extremes (5th gen) in an office environment. All of these Airports would have direct ethernet connections to the switch. Is this possible with the 802.11n spec and the n

  • Configure Keyboard Layout - why is this screen being displayed?

    Hello, I have a problem. I want the Solaris 10 installation to be hands-off. I modified the sysidcfg file, everything wors fine, but unfortunately after the execution of the finish script (at the end of the installation) this screen is being displaye

  • HKCU registry and the start up application which one will ready first

    Hello guys, here is my question. When create a new user in windows8.1, and I write a service to launch my appA to do something. and my appA will read the registry at HKCU, but failed! Then I restart appA, read the registry again, it success!  I guess

  • Internet over USB

    Can I get internet over the usb port on the Airport Express? For example using it to connect to a TiVo?