Summing Prices Day By Day
Oct 23, 2013
Let suppose that we have a table which look like this
BillDate Price
01.01.2013 2.00
01.01.2013 1.00
02.01.2013 3.00
02.01.2013 2.00
03.01.2013 1.00
I would like to sum a prices day by day and output to be like this
BillDate SumDaylyPrice
01.01.2013 3.00
02.01.2013 5.00
03.01.2013 1.00
To point I’ve reached myself is a query:
SELECT BillDate, (SELECT SUM( Price) FROM Table1 ) AS SumDaylyPrice
FROM Table1
WHERE BillDate BETWEEN
(SELECT Min(BillDate) FROM Table1)
AND
(SELECT Max(BillDate) FROM Table1)
GROUP BY BillDate
but this doesn’t work- summing everityng
I don’t know how to indicate in first row of query
SELECT BillDate, (SELECT SUM( Price) FROM Table1 WHERE DATE = ????) AS SumPrice
a WHERE clause for every day separately.
View 2 Replies
ADVERTISEMENT
Sep 22, 2007
Dear all
I have a company that sells fruit and vegetables to the catering industry.
I take orders in the evening for the next day, and buy my fruit and vegetables from wholesale market to deliver to my customers on the next day.
I have sage simply accounting.
I have to enter invoices day before I print them, so I can get a list of items i should buy next day (and also sort them into different routes)
My question is, is there a way to update all the prices on the active invoices (i.e. not printed or posted) for the previous day, after I enter new prices for the fruit and vegetables???
I need this as at the moment I hava to go into individual invoices and enter the products and quantities again.
Many thanks
hh
View 4 Replies
View Related
Feb 5, 2008
I want to update price of products table from an imported table B.
Here is the code:
Code Snippet
update dbo.tbl_product
set product_wholesale_price = (SELECT dbo.B.WS FROM dbo.B
where dbo.tbl_product.product_id = dbo.B.product_code)
But I am getting the following error:
Msg 107, Level 16, State 3, Line 1
The column prefix 'dbo.B' does not match with a table name or alias name used in the query.
Msg 107, Level 16, State 3, Line 1
The column prefix 'dbo.B' does not match with a table name or alias name used in the query.
Please tell me where I am wrong..or is there a better way to do it?
View 5 Replies
View Related
Feb 17, 2013
I have 2 test tables one for stock and one for prices.
I need to select all the rows from Stock but also the price on the stock but the price table doesn't always have the date, so I can not do stock date = price date.
What it needs to do is if the Stoc Date isn't in the price table use the price before... this would also have to be able to run on my rows...
-- Create Test Table (not sure if dates USA or UK format on your machine...
CREATE TABLE [dbo].[TheStockLedger](
[EntryID] [int] NULL,
[TheDate] [datetime] NULL,
[StoreCode] [nvarchar](50) NULL,
[Item] [nvarchar](50) NULL,
[ColorCode] [nvarchar](50) NULL,
[code]....
View 10 Replies
View Related
Apr 24, 2008
Hi,
I have a SQL2005 db for tracking the prices of products at multiple retailers. The basic structure is, 'products' table lists individual products, 'retailer_products' table lists current prices of the products at multiple retailers, and 'price_history' table records when the price of a product changes at any retailer. The prices are checked from each retailer daily, but a row is added to the 'price_history' only when the price at the retailer changes.
Database create script:
http://www.boltfile.com/directdownload/db_create_script.sql
Full database backup:
http://www.boltfile.com/directdownload/database.bak
Database diagram:
http://www.boltfile.com/directdownload/diagram_0.pdf
I have the following query to retrieve the price history of a given product at multiple retailers:
SELECT
price_history.datetimeofchange, retailer.name, price_history.price
FROM
product, retailer, retailer_product, price_history
WHERE
product.id = 'b486ed47-4de4-417d-b77b-89819bc728cd'
AND
retailer_product.retailerid = retailer.id
AND
retailer_product.associatedproductid = product.id
AND
price_history.retailer_productid = retailer_product.id
This gives the following results:
2008-03-08 Example Retailer 22.3
2008-03-28 Example Retailer 11.8
2008-03-30 Example Retailer 22.1
2008-04-01 Example Retailer 11.43
2008-04-03 Example Retailer 11.4
The question(s) I have are how can I:
1 - Get the price of a product at a given retailer at a given date/time
For example, get the price of the product at Retailer 2 on 03/28/2008. Table only contains data for Retailer 1 for this date, the behaviour I want is when there is no data available for the query to find the last data at which there was data from that retailer, and use the price from that point - i.e. so for this example the query should result in 2.3 as the price, given that was the last recorded price change from that retailer (03/08/2008).
2 - Get the average price of a product at a given retailer at a given date/time
In this case we would need to perform (1) across all retailers, then average the results
I'd really appretiate anyone's help on this :)
many thanks in advance,
dg
View 17 Replies
View Related
Mar 13, 2007
I would like to use analysis services to analyze stock prices.
I want to find conditional probabilities:
P (YpriceChg >= 10% s.t. Ydate between A and B| X Price Chg >= 20%)?
€¦ Like given a price change of X percent or greater, predict the probability of a price change of Y percent or greater, within a specified time window (like 2 days, 3 months etc.).
I also want to add a support filter, like:
N > 30 cases (i.e., there have been at least 10 instances of a 10% or greater price change, for the chosen time window)
I have a database of prices, monthly, daily, etc. I also have a number of cols that compute statistics such as pChg1M, pChg-1M, vChg1d. Like price chg 1 month forward, price change 1 month backward, volumeChg1d forward. Ideally, I would like to minimize the column flags necessary for the experiment. Can you offer some hints, as far as setting up appropriate columns/flags and choosing a algorithm (maybe decision trees, association rules, or NB)?
View 1 Replies
View Related
Oct 12, 2006
Hi,I would like to change my select to generate table that will resultsThat will haveService, Room, Season A, Season BWhere season names are saved in database and in their colums I would like to have pricing for rooms.How can I accomplish this - I dont know how to clearly explain - hope SQL will help: String selectCommandBookings = "SELECT dbo.Service.Name AS Service, dbo.Room.Name AS Room, dbo.Season.Name AS Season, dbo.HSRSeason.Price"; selectCommandBookings += " FROM dbo.Season INNER JOIN"; selectCommandBookings += " dbo.HSRSeason ON dbo.Season.SeasonID = dbo.HSRSeason.SeasonID INNER JOIN"; selectCommandBookings += " dbo.HSR ON dbo.HSRSeason.HSRID = dbo.HSR.HSRID INNER JOIN"; selectCommandBookings += " dbo.Room ON dbo.HSR.RoomID = dbo.Room.RoomID INNER JOIN"; selectCommandBookings += " dbo.Service ON dbo.HSR.ServiceID = dbo.Service.ServiceID"; selectCommandBookings += " WHERE (dbo.HSR.HotelID = '" + hotelID + "')"; selectCommandBookings += " ORDER BY dbo.Service.Name, dbo.Room.Name, dbo.HSRSeason.Price";
View 2 Replies
View Related
Dec 30, 2011
Assume you have a table called Tick with 2 columns
(
tickId bigint IDENTITY(1,1)
, price int -- usually money data type, making it int for simplicity
)
I am tasked with creating bars that are 10 units long.
Now the catch is I'm not looking for the tickId where price is >= t1(price) + 10 where t1(price) is the price for the first row where tickId = 1. (it could also be where price <= t1(price) - 10)
Here is sample data:
1, 25
2, 26
3, 23
4, 26
5, 27
6, 30
7, 34
8, 32
9, 30
10, 33
What I am looking for are rows 3 (23) and 7 (34)
Currently I have:
Code:
DECLARE @tickDiff int
SET @tickDiff = 10
DECLARE @r1TickId bigint
[Code].....
This seems to work but it is taking multiple minutes to run for about 50k rows of data (which I created off of the 24 million row table I have just looking at data from today). So it takes ~5 minutes to create the first bar which is not acceptible.
If my logic above seems acceptable are there any indexes you could recommend. Database engine tuning advisor didn't find any.
View 2 Replies
View Related
Aug 9, 2013
Find out the models and prices for all the products (of any type) produced by maker B.
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)
select product.type,
pc.price as pcprice,
laptop.price lapprice,
pc.model as pcmod,
laptop.model as lapmod
from product
join
pc on product.model=pc.model
join
laptop on laptop.model=product.model
where maker = 'B'
the syntex runs but its not displaying any results + I know that I have some extra columns there but its for some thing else I was trying
View 3 Replies
View Related
Jul 20, 2005
I am trying to check a list (MyList) against another List(SupplierList).I want sum the Qty's of UniqueID on MyList and extract the sum of thesame UniqueId's on SupplierList.BTW There are more than one instances of Unique Id on each list.The Script below is providing me with the correct answer for someproducts (UniqueId), but incorrect amounts for others.The incorrect answer is always a multiple of the correct answer.What am i doing wrong???Regards,CiaránSELECT MyList.[Unique ID], SupplierList.[Unique ID], Sum(MyList.[SHP_QTY]), Sum (SupplierList.[Qty new])FROM MyList LEFT OUTER JOIN SupplierList ON MyList.[Unique ID]= SupplierList.[Unique ID]GROUP BY MyList.[Unique ID], SupplierList.[Unique ID]
View 1 Replies
View Related
Apr 30, 2008
Hi,
I'm trying to get a sum but not doing too well. I think I need a subquery but am unsure how to phrase it.
Problem:
I need to sum timesheet hours logged at work-code level to project-level (for named projects), where a project consists of 0-to-many work-codes. The 'Project' table is used for both projects and work-codes; the 'pr_code' contains the unique code (i.e. the work-code or the project-code), 'pr_master' field contains the parent. The Timesheet table will contain pr_code's for work-codes, but won't contain an entry for a work-code if no-one has logged any time to a work-code.
Sample input:
Timesheet table
===============
pr_code|ts_hours
QWER.01|6
QWER.01|7
QWER.02|3
QWET.01|2
Project table
=============
pr_code|pr_master
QWER.01|QWER
QWER.01|QWER
QWER.02|QWER
QWET.01|QWET
QWER|QQQQ
QWET|QQQQ
QWEY|QQQQ
Intended output:
For named projects QWER, QWET & QWEY:
QWER|16
QWET|2
QWEY|0
I've got the following so far which almost gets there, but appears to be summing up as it goes i.e. QWER=16, QWET=18, QWEY=18:
SELECT p1.PR_Master AS Expr1, SUM(Timesht.TS_Hours) AS Expr2
FROM Timesheet LEFT OUTER JOIN
Projects ON Timesheet.PR_Code = Projects.PR_Code LEFT OUTER JOIN
Projects p1 ON Timesht.PR_Code = p1.PR_Code
WHERE (p1.PR_Master IN ('QWER', 'QWET', 'QWEY'))
GROUP BY p1.PR_Master
Any help most appreciated.
View 5 Replies
View Related
Jun 6, 2008
This is a working 12 month intrest equation. I used this for the layout section but I am trying to take this and it gives me the correct values. But what I need to do next is have it sum those values.
I tried =SUM( whole expression but that didnt work) you can laugh at me I know but any help would be great!
=Switch(Fields!eqprecdt.Value< CDate("1 Jan 2007"),Fields!bookvalue.Value*datediff("d",Now(),#1/1/2007#)* .07/365,Fields!eqprecdt.Value> CDate("1 Jan 2007"), Fields!bookvalue.Value * datediff("d",Now(),Fields!eqprecdt.Value)* .07/365)*-1
View 5 Replies
View Related
Feb 5, 2008
As my name shows I am about read to pull my hair out on this and will take any help that I can get.
I have a table with the following values
field1,field2,field3
a | p | 1
a | n | 1
a | p | 2
b | p | 2
b | p | 2
b | n | 3
I am grouping by first column
a
p 1
n 1
p 2
-------------------
a 3 1
b
p 2
p 2
n 3
------------------
b 4 3
What I want to do if it have a value of p I want the value in one column if it has a value of n I want it in another column.
The columns are not a problem, I use a iif statement iif( field2 = p, value, 0) iif ( field2 = n, value, 0)
the problem comes when I try to total the columns.
I was trying to use the =sum(field3) in my group total.
the above example is what I want to see the below example is what I get.
a
p 1
n 1
p 2
-------------------
a 4 4
b
p 2
p 2
n 3
------------------
b 7 7
I hope this makes some since to someone out there that can help me out.
I am getting kind of thin in the hair department so I cannot afford to loose any more.
View 3 Replies
View Related
Jul 20, 2006
I need help in summing a column by dates in the format of "YYMMDD". We have multiple orders of the same product each day. I am importing this table to Excel and creating a dashboard. My ultimate goal is to reduce the size of the imported table and still have daily totals of each product. We run thousands of line orders per class which really bogs down Excel. My table in MS Query is as follows (the actual table contains approximately 8,000 lines per month):
date prod class qty
060101 a101 1a 100
060101 a101 1a 100
I would like to have the following:
date prod class qty
060101 a101 1a 200
Any other suggestions would be greatful!!
Thanks in advance
View 4 Replies
View Related
Jun 4, 2007
Hi,I need some help in summing each column in a gridview.id name sun mon tue wed total1 Tim 5 6 5 10 263 Sam 6 6 6 5 23The above is how the gridview looks like. In the database, I have all the fields except for total. So, I know I have to use the SUM function in SQl to get the Total. So, I am wondering how do I sum each column to get the total. I have something like this but it doesn't work:"SELECT ID, name, Sun, Mon, Tue, Wed, SUM(Sun + Mon + Tue + Wed) AS Total FROM testTable"Please helpahTan
View 7 Replies
View Related
May 7, 2008
I am quite new in sql. I am writing a report which takes data of one same column and summing them according to the type as described in another column("TR_1"."TTYPE"). So far I have succeeded to get the sum of only one type at a time (by putting WHERE "TR_1"."TTYPE" = or not equal the desired type). For example: I want to create two columns, one showing the sum of the budget and the other the some of the actuals: here is my SQL instruction (the column "TR_1"."TTYPE" give the record type):
******************************************************************
SELECT SUM("TR_1"."AmountLCU")*-1 "Budget",rtrim("TR_1"."COSTCENTER") "Cost Centre",rtrim("TR_1"."ACCOUNT") "Account Num",rtrim("TR_1"."DONOR") "Donor Num", "TR_1"."AmountLCU"*-1 "Amount","TR_1"."TTYPE", rtrim("TR_1"."ACTIVITY") "Activity Code" FROM "scalaDB"."dbo"."A_GL0601_PREVIOUS" "TR_1"
WHERE NOT ("TR_1"."TTYPE"='' OR "TR_1"."TTYPE"='a' OR "TR_1"."TTYPE"='c') AND NOT ("TR_1"."COSTCENTER"=N'' OR "TR_1"."COSTCENTER"=N'0000') AND (("TR_1"."ACCOUNT">=N'26' AND "TR_1"."ACCOUNT"<N'7100') OR ("TR_1"."ACCOUNT">N'7100' AND "TR_1"."ACCOUNT"<=N'7999'))
GROUP BY "TR_1"."COSTCENTER","TR_1"."ACCOUNT","TR_1"."DONOR","TR_1"."ACTIVITY","TR_1"."AmountLCU","TR_1"."TTYPE"
**********************************************************************
Note: the report is written in Crystal reports and the database is SQL Server (not sure of the version)
Thanks in advance
I.Shaame
View 9 Replies
View Related
Mar 16, 2006
Hello, This is my first post so please be kind. I have been attempting to convert a query I built in MS Access for use in MSSQL 2000, the syntax for these is different so I was frustrated to find out I could not use the access query.
I have 4 columns one containing a user Id and the others costs, I wish to total the costs per user ID at the end of each row.
So far I have managed to convert about half of my access query, this gives mev the clientID's and costs in columns but I cannot for the life of me get the costs in a total. It's annoying because my access query works perfectly.
This is my Access query:
SELECT DISTINCT Holiday_Bookings.ClientID, Holiday_Bookings.Booking_Cost, Room_Facilities.FacilityCost, Rooms.CostPerNight,
Rooms!CostPerNight*Nights_Stayed+Holiday_Bookings!Booking_Cost+Room_Facilities!FacilityCost AS TotalCost,
[TotalCost]*17.5/100+[TotalCost] AS [Total+VAT]
FROM Room_Facilities INNER JOIN (Hotels INNER JOIN (Holiday_Bookings RIGHT JOIN Rooms ON Holiday_Bookings.ClientID = Rooms.ClientID) ON Hotels.HotelID = Rooms.HotelID) ON Room_Facilities.FacilityID = Rooms.FacilityID;
And this is what I have been able to salvage into MSSQL format:
SELECT
Holiday_Bookings.ClientID,
Holiday_Bookings.Booking_Cost,
Rooms.CostPerNight,
Room_Facilities.FacilityCost
FROM
Rooms
INNER JOIN Room_Facilities ON (Rooms.FacilityID = Room_Facilities.FacilityID)
INNER JOIN Holiday_Bookings ON (Rooms.Clients_ID = Holiday_Bookings.ClientID)
How can I total the three columns and add the tax?
View 3 Replies
View Related
Nov 23, 2005
Hello,Here is a brief summary:Table 1 = All Accounts- with fields such as Customer ID and Account #Table 2 = Deposit Balance Table- with fields such as Account #, BalanceTable 3 = Loan Balance Table- with fields such as Account #, BalanceAll accounts are either deposit accounts or loan accounts. What I needto do is to gather information about total balances in both depositsand loans for each customer. I haven't been able to hit the right queryfor doing this. I can easily get information about one or the other,such as the following:SELECT All_Accounts.Customer_ID, COUNT (DISTINCT(Deposit_Balance_Table.Account_Number)), Sum(Deposit_Balance_Table.Balance)FROM Product_Table, Deposit_BalanceWHERE (Product_Table.Account_Number=Deposit_Balance.Acco unt_Number)GROUP BY Product_Table.Customer_ID ORDER BY 1Which will give me one row for each user, and show me the total numberof deposit accounts each customer has and a sum of the balances in eachof those accounts. I can make a similar query involving Loan Accounts.As soon as I try to draw both, however, I wind up below my depth.Something to do with the handedness of my joins, I believe. Often Iwill get one column of information (either deposits or loans), or thequery will fail because the join I'm attempting is invalid, etc. I needto take every row in the All_Accounts table, match each one to itsbalance in either the Deposit or Loan table, and then group them all bythe Customer ID and sum them, so that I can find out the totalrelationship balance per customer. Any help would be appreciated.
View 5 Replies
View Related
Jul 20, 2005
We recently added a new database at the company. It has only onepurpose - to hold massive amounts a daily data generated by telephonecalls on a network.The amount of data was so large (several gigabytes a day) that the guywho set up the database creates a new table for it each day.His thinking was that if we only need to query one day's worth of datathen it would be a lot faster to query a table with one day's datathan having to query many days of data in one table.I see his reasoning. Any comments or alternatives to this schemewould be appreciated.Here's the question though...I'm writing a front end for this and waswondering if the most efficient way to query and sum data acrossmultiple tables (days) is in the form of the following statement.Suppose three days of worth of data are wanted:select sum(ET) from (select sum(vc_elapsed_time) AS ET fromswitch2030608 where init_cell_info_cell = 196 union all selectsum(vc_elapsed_time) as ET from switch2030609 whereinit_cell_info_cell = 196 union all select sum(vc_elapsed_time) as ETfrom switch2030610 where init_cell_info_cell = 196 ) tIn my front end, based on user input, I plan to keep extending thisstatement with more union alls. Is this the best way to implement thegoal of this query?-David
View 1 Replies
View Related
May 12, 2008
I have a report with several columns which include Status(0,1,2) and Time in hours. I want to be able to total up the time for each status. I Sum up the all of the fields fine. I'm new to reporting services so any help would be appreciated. Thanks
View 3 Replies
View Related
Nov 9, 2007
In below table, the light blue rows, represents the subgroup I am trying to sum up.
The value in the "Inventory Value" contains the latest inventory value for said inventory.
Light green row is grouped by Store name, Light blue is grouped by inventory name. the expression in Inventory row for the inventory value column is =First(Fields!InventoryValue.Value).
Doing a store summation, sums up all detailed values. For example in Store A, instead of 70K, the sum would be 130K... double summing the toy soldiers and cute dolls inventory. Is there a way to do the "correct" summation or a different approach to this? Thanks!
STORE
TOTAL STORE INVENTORY VALUE
INVENTORY
% OF STORE INVENTORY
INVENTORY VALUE
WARNING DATE
STORE A
1,000,000.00
TOY SOLDIERS
2.00%
20,000.00
20,000.00
11/5/2007
20,000.00
11/2/2007
PLUSH TOYS
1.00%
10,000.00
10,000.00
11/5/2007
CUTE DOLLS
4.00%
40,000.00
40,000.00
11/2/2007
40,000.00
10/31/2007
1,000,000.00
7.00%
70,000.00
STORE B
10,000,000.00
TOY SOLDIERS
0.20%
20,000.00
20,000.00
11/5/2007
20,000.00
11/2/2007
PLUSH TOYS
0.10%
10,000.00
10,000.00
11/5/2007
CUTE DOLLS
0.40%
40,000.00
40,000.00
11/2/2007
40,000.00
10/31/2007
10,000,000.00
0.70%
70,000.00
View 4 Replies
View Related
Apr 14, 2008
Hi, I'm converting an existing report to an RDLC report using VS2008 C#. I'm a relative newbie to creating RDLC files, and I'm having a problem with one part of the report. I have three Table controls on the report. Two show detail breakouts from different data sources and the third Table is supposed to show some grand total information by summing the totals of the first two tables. Since it appears that a table can only be bound to one datasource, I can't seem to figure out how to get a sum by peaking into the totals of the first two tables. How can I do this?
Thanks,
Ian
View 4 Replies
View Related
Apr 22, 2008
Hi There,
I have the following query:
SELECT NATNLACCT, IDCUST, TEXTSNAM, AMTBALDUEH
FROM
VIEW_ARCUS
where amtbaldueh != .000
order by NATNLACCT
but i want to display the data something similar as below. How do I create a column to display with the natinlacct name(I have many) concatenated to Total and then sum amtbaldueh?
Natinlacct idcust textsnam amtbaldueh
Doda 1234 abcd $101
Doda 5678 efgh $200
Doda 9876 ijkl $300
Doda Total $601
Nava 5847 jhgf $230
Nava 5487 lfde $130
Nava 3587 lrsd $100
Nava Total $460
Thanks
Rhonda
View 5 Replies
View Related
Jun 16, 2008
I have a question on how to sum data by a certain date range. Here is the data I'm looking at. I have volume measured usually (but not always) every day. I want to sum the volume from the 2nd of the month to the first of the next month. I want to do this for every month. I have the columns of my data listed below. Can anyone help me with this? I've been trying to read up on it, but I'm not finding anything.
Entity Date Measured Volume
1 4/01/2008 5
1 4/02/2008 4
1 4/03/2008 6
1 4/04/2008 5
1 4/08/2008 7
1 4/12/2008 8
1 4/13/2008 5
1 4/14/2008 7
1 4/25/2008 8
1 4/30/2008 9
1 5/01/2008 6
1 5/02/2008 8
Thanks in advance for any help!
View 4 Replies
View Related
Jul 9, 2014
I am working with a MS SQL database associated with SCCM 2007. SCCM collects software product usage data, and I am tasked with generating a report that will return results between two user-chosen date ranges. I set up prompts for month, year, endmonth, endyear. They would enter 2, 2014, 4, 2014 for example. Timekey would equal 201402, endtimekey = 201404. The tables I am concerned about look like this:
v_MonthlyUsageSummary
TimeKey ResourceID FileID UserID UsageCount TSUsageCount UsageTime LastUsage
201402108343 253362240038122 0 2550272014-02-28 13:29:39.000
201402108340 253362240665 2 0 122014-02-27 15:58:13.000
201402108932 253362231708 0 10 216702014-02-14 20:41:35.000
201403124035 504006542145 15 0 1756292014-03-31 19:37:37.000
201403124036 504006537579 46 0 7737112014-04-01 00:00:00.000
v_SummarizationInterval
TimeKey IntervalStart
2013102013-10-01 00:00:00.000
2013112013-11-01 00:00:00.000
2013122013-12-01 00:00:00.000
2014012014-01-01 00:00:00.000
2014022014-02-01 00:00:00.000
2014032014-03-01 00:00:00.000
2014042014-04-01 00:00:00.000
2014052014-05-01 00:00:00.000
2014062014-06-01 00:00:00.000
2014072014-07-01 00:00:00.000
The problem is I only know how to grab one timekey, but I need to combine multiple timekeys to sum up the usage counts for each workstation.
Here is the full query.
declare @TimeKey int
declare @months float
declare @endTimeKey int
set @TimeKey=100*@Year+@Month
set @endTimeKey=100*@endYear+@EndMonth
select @months=DATEDIFF(d,@timekey,@endTimeKey)
[Code] .....
View 20 Replies
View Related
Jan 10, 2008
Hello,
Here's one way to sum only the top 5 (greatest 5) values per group.
I assume there is a table called IdValues that contains two columns: id int, value int.
declare @lastId int
declare @value int
declare @count int
declare @idList varchar(5000)
declare @valuelist varchar(5000)
set @count=0
set @lastId = -1
set @value = 0
set @idList=''
set @valuelist=''
select
@count=(case when @lastId<>id then 1 else @count+1 end),
@value=(case when @lastId<>id then value when @count<=5 then @value+value else @value end),
@idList=(case when @lastId<>id then cast(id as varchar)+','+@idList else @idList end),
@valuelist=(case when @lastId<>id then cast(@value as varchar)+','+@valuelist else cast(@value as varchar)+','+right(@valuelist,len(@valuelist)-charindex(',',@valuelist)) end),
@lastId=id
from IdValues
order by id desc, value desc
select @idList,@valuelist
It's a funny approach. I'd be interested to see a better method. In MySQL it is possible to do this much better and have it produce an actual resultset (since MySQL allows you to assign variables and product a resultset in the same query).
I also noticed something interesting. If you do any operation on the order-by columns, the query doesn't work. For example, if I do:
order by id+0 desc, value desc
something funny happens and you only get one id and one value in the list variables. Maybe someone else who actually some idea of how SQL Server works can explain this.
Thanks,
Thomas
View 3 Replies
View Related
Jul 28, 2006
Hi everyone, I have some trouble writing a SQL stored procedure thatcan do the following:We have data in one table in numeric form, but we want to sum the datain this table based on the values of two different alpha fields. Toillustrate, let me write the following example:Table with these records:A B 1.1 2.2 Blah1 Blah1A B 2.3 5.6 Blah2 Blah2B C 7.8 9.1 Blah3 Blah3B C 4.5 1.0 Blah4 Blah4R F 1.1 4.3 Blah5 Blah5B A 3.1 2.7 Blah6 Blah6I need to write a query that will return the following result set fromthe above table:A B 3.4 7.8 Blah1 Blah1B C 12.3 10.1 Blah3 Blah3R F 1.1 4.3 Blah5 Blah5B A 3.1 2.7 Blah6 Blah6If the alphanumberic keys are the same, the sum the numeric columns upwhilst displaying one one of the records, the blah fields don't matterif one only one is displayed. Can anyone recommend the best way to dothis? I'm running MS SQL 2005.Thanks,Herman
View 1 Replies
View Related
Jun 23, 2015
I have a table with duration values for different machine states. I 'm trying have a sum of the duration value of each state ( the duration sum , was an earlier question).
declare
@tblDurations
TABLE
(StateName
nvarchar(30),Duration
nvarchar(30))
[code]...
I want the output to have sum of the duration ( from my function ), grouped by the state.So output should be :
Breaks 00:02:03:40
Meetings 00:00:01:50
Running 15:21:07:16
I think this can be done with windows functions, but how I don't know.
View 10 Replies
View Related
Jun 29, 2007
What I need to do in seperate a group of numbers into two different categories based on a phase code. I have acheived this through two conditional statements, but when I try to total the numbers that were returned for each group I receive an #error.
This is an example of the switch statement I used in order to return the correct values for the Implemenataion.
=Switch(Fields!Phase_Code.Value="PILOT", Fields!LedgerQuantity.Value, Fields!Phase_Code.Value="DATAMIGRAT", Fields!LedgerQuantity.Value/2, 1=1, "")
I've tried several different methods for aggregating the numbers that are returned.
=SUM(Switch(Fields!Phase_Code.Value="PILOT", Fields!LedgerQuantity.Value, Fields!Phase_Code.Value="DATAMIGRAT", Fields!LedgerQuantity.Value/2, 1=1, ""))
I've tried substituting a 0 in for the "" at the end of each statement. I've also tried to take the first statement and put it into its own table field named ImplementationLedger, and them summing it. ie. =SUM(Fields!ImplementationLedger.Value)
Please Help!
View 1 Replies
View Related
Nov 6, 2006
Hello again
How do I sum up and group numeric values into one output column in SSIS?
I have data that looks like this:
Refno date credit amount
11675 1987-04-23 7.03 13501.27
and I want to add the credit and amount columns together and output them as one column, In T-SQL, i'd do this:
SELECT Refno, SUM(Credit + Amount)
FROM Transfer
GROUP BY Refno, Date
I could add this SQL into my SSIS package easily enough but I wan't to learn how to do it the SSIS way
View 4 Replies
View Related
Dec 3, 2006
I am working on a stock price analysis project. Stock prices are stored in SQL Server as tick by tick data (that means in a high frequency) and need to be grouped by minutes in order to display them as as high, low, open and close prices in a candlestick or similar chart.
The fields in the table are:
Time (for every stock price tick)
Price (stock price)
Symbol (of the stock)
A sample time series would look like this:
11:45:01 $22.11 MSFT
11:45:02 $22.10 MSFT
11:45:04 $22.25 MSFT
...
...
...
11:45:58 $22.45 MSFT
11:46:03 $22.22 MSFT
11:46:08 $22.25 MSFT
...
...
...
11:46:59 $22.45 MSFT
The result of the SQL query should be:
Symbol Time Open High Low Close
MSFT 11:45 $22.11 $22.45 $22.10 $22.45
MSFT 11:46 $22.22 $22.45 $22.22 $22.45
This is the SQL statement I came up with but obviously doesn't work:
SELECT DATEPART(Minute,Time), MIN(Price), MAX(Price) FROM dbo.TimeSales WHERE Symbol='MSFT' GROUP BY DATEPART(Minute,Time)
I would appreciate any suggestions.
Thank you!
View 10 Replies
View Related
Mar 20, 2014
I have a query that brings in a result from a table that I have to display as a negative, so I use ABS (tbname.fieldname) *-1
This works fine. (Learnt it here from a previous post.)
I have another query that brings in a result from the same table but as a postive. So that works fine too.
Now, I need to sum them together in a new query. If the total value is a positive, fine. If the total value is a negative, it displays as a positive.
My question. Is it actually possible to achieve what I'm trying to do?
Output example below - narrow result for testing.
idpt2 Value2SumQty
N1141307-80970 3.80 2
N1141S2G00009D070 26.16 2
The 3.80 is correct, it is a positive.
The 26.16 is incorrect as it is the output from sum 235.44 -261.6 so I need it to display as -26.6
View 9 Replies
View Related
Sep 12, 2013
field prodDate puts out values as such:
8/12/2013 7:50:15
8/12/2013 7:51:03
8/12/2013 7:53:42
8/12/2013 7:54:12
8/12/2013 7:56:02
...
...
8/12/2013 14:57:57
8/12/2013 14:59:59
I'd like to get a time span sum beginning with the first prodDate entry and ending with the last.
The idea is I'll then use that to divide lbs produced, thus giving me a gauge for lb per hour.
View 3 Replies
View Related