Subquery For Totals
Jul 17, 2007
Hi,
I use the following query in my stats page to find the unique visitors and the pages they visited per day in a given month.
SELECT
CONVERT(CHAR(10),LogDate,103) As Date_,
Count(DISTINCT LogRemote_Addr) As Visitors,
Count(Lid) As Pages
FROM Log
WHERE LogMonth=7
Group by CONVERT(CHAR(10),LogDate,103)
ORDER BY CONVERT(CHAR(10),LogDate,103)
I would like to have the totals (Sum) of the "Visitors" and "Pages" also for the given month.
I think I have to use a subquery to accomplish that but I can't figure it out. I would appreciate your help.
Thanks,
Deni
www.tabletennis.gr
View 9 Replies
ADVERTISEMENT
Aug 1, 2013
I have a Master table with a OrderNbr which is also contained in the Detail table.
It's a 1 to Many relationship, respectively.
I want to update the MASTER.FinalizedDate using a "select top 1 FinalizedDate order by FinalizedDate DESC" from the Detail table but the clause is ALL the Status have to be "F". So OrderNbr 12345 should not get updated because it contains a 'O'. OrderNbr 67899 should get updated in the Master table to 2/26/2013 because all have a 'F' and the last date to post is the official finalized date.
Here is what I came up with.......so far, but not sure how to work in the Status piece on 1 to M.
The rub here is that even if one row has the 'O' status I want to ignore the update. If all have the 'F' then I want the udpate to happen.
Update MASTER
Set FinalizedDate = (select top 1 d.FinazliedDate from Detail d
where m.OrderNbr = d.OrderNbr
and d.Status not in ('O')
Order by FinalizedDate DESC)
From MASTER m
How do I not include all 3 rows for OrderNbr 12345 because one row has the Status "O" in the DETAIL table?
Here are the table looks........
MASTER
OrderNbr Ytotals Ztotals Xtotals Finalized Date
12345$1,500$1,500$1,200
67899$1,200$1,100$900
DETAIL
OrderNbrItemNbr PriceStatusFinalized Date
1234563453453 $1,400F1/2/2013
12345554444 $1,500F1/2/2013
12345545444 $2,200O NULL
67899333334 $899F2/24/2013
678993434344 $659F2/24/2013
67899434676 $499F2/26/2013
6789978888 $599F2/24/2013
View 3 Replies
View Related
May 9, 2015
I have some data grouped in a table by a certain criteria, and for each group it is computed a subtotal for the group. Of the values from each of the group, I want to create a grand total on the report by adding every subtotal from each group.
Example:
...
....
Group1 Value
10
20
Sub Total 1: 30
Group2 Value
15
25
Sub Total 2: 40
Now, I would like to be able to add subtotal 1 (30) to subtotal 2 (40) and my grand total would be 70. Can I accomplish this task in SSRS?
View 5 Replies
View Related
Oct 2, 2006
I have been providing sales data for a few months now from a table that is set up like this:
Date WorkDay GasSales EquipmentSales
9/1/2006 1 100.00 200.00
9/4/2006 2 50.00 45.00
etc.
As can be seen, the data is daily, i.e., on the first workday of September we sold one hundred dollars in gas and two hundred dollars in equipment. On the second workday of September we sold fifty dollars in gas and forty-five dollars in equipment.
Now, however, the data I have to pull from is cumulative. So, using the last table as an example it would look like this:
Date_WorkDay_GasSales_EquipmentSales
9/1/2006 1 100.00 200.00
9/4/2006 2 150.00 245.00
etc.
To make things more complicated, the powers that be wanted this data presented in this fashion:
Total Sales:
1_2_etc.
300.00 95.00 etc.
So, I have been doing a pivot on a CRT to get the data to look like I want. The code is like this:
with SalesCTE (Month, WorkDay, [Total Sales])
as
(
SELECT
datename(month, cag.date),
cag.WorkDay AS [Work Day],
sum(cag.sales_gas + cag.sales_hgs) AS [Total Sales]
FROM CAG INNER JOIN
Branch ON CAG.[Oracle Branch] = Branch.OracleBranch
group by cag.date, cag.WorkDay
)
select * from SalesCTE
pivot
(
sum([Total Sales])
for WorkDay
in ([1],[2],[3],[4],[5],,[7],,[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23])
) as p
So, my question is:
How do I get the data to give back daily totals instead of the cumulative amounts for each workday? If the query was a simple one, I'd do something like
select [1] as [Day 1], [2]-[1] as [Day 2], [3]-[2] as [Day 3], etc.
but the query is far from normal, with the CRT and the pivot. I can't seem to get it to work how I'd like.
Any advice/answers? Thanks in advance!!!
P.S. I don't know how to get it to quit with the freakin' smileys.... I suppose you can figure out what my code is really supposed to look like above. Needless to say, it doesn't include a devil face and a damn music note...
View 12 Replies
View Related
Apr 26, 2008
hello friends.. I am newbie for sql server...I having a problem when executing this procedure .... ALTER PROCEDURE [dbo].[spgetvalues] @Uid intASBEGIN SET NOCOUNT ON; select DATEPART(year, c.fy)as fy, (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1% JRF' ) as survivorship, (select contribeamount from wh_contribute where and contribename like 'Gross Earnings' and ) as ytdgross, (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1.5% JRP') as totalcontrib, from wh_contribute c where c.uid=@Uid Order by fy Asc .....what is the wrong here?? " Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."please reply asap...
View 1 Replies
View Related
Jul 20, 2005
I am getting 2 resultsets depending on conditon, In the secondconditon i am getting the above error could anyone help me..........CREATE proc sp_count_AllNewsPapers@CustomerId intasdeclare @NewsId intset @NewsId = (select NewsDelId from NewsDelivery whereCustomerId=@CustomerId )if not exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count( NewsPapersId) from NewsPapersendif exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count(NewsDelId) from NewsDelivery whereCustomerid=@CustomeridendGO
View 3 Replies
View Related
Mar 6, 2008
I am getting an error as
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
while running the following query.
SELECT DISTINCT EmployeeDetails.FirstName+' '+EmployeeDetails.LastName AS EmpName,
LUP_FIX_DeptDetails.DeptName AS CurrentDepartment,
LUP_FIX_DesigDetails.DesigName AS CurrentDesignation,
LUP_FIX_ProjectDetails.ProjectName AS CurrentProject,
ManagerName=(SELECT E.FirstName+' '+E.LastName
FROM EmployeeDetails E
INNER JOIN LUP_EmpProject
ON E.Empid=LUP_EmpProject.Empid
INNER JOIN LUP_FIX_ProjectDetails
ON LUP_EmpProject.Projectid = LUP_FIX_ProjectDetails.Projectid
WHERE LUP_FIX_ProjectDetails.Managerid = E.Empid)
FROM EmployeeDetails
INNER JOIN LUP_EmpDepartment
ON EmployeeDetails.Empid=LUP_EmpDepartment.Empid
INNER JOIN LUP_FIX_DeptDetails
ON LUP_EmpDepartment.Deptid=LUP_FIX_DeptDetails.Deptid
AND LUP_EmpDepartment.Date=(SELECT TOP 1 LUP_EmpDepartment.Date
FROM LUP_EmpDepartment
WHERE EmployeeDetails.Empid=LUP_EmpDepartment.Empid
ORDER BY LUP_EmpDepartment.Date DESC)
INNER JOIN LUP_EmpDesignation
ON EmployeeDetails.Empid=LUP_EmpDesignation.Empid
INNER JOIN LUP_FIX_DesigDetails
ON LUP_EmpDesignation.Desigid=LUP_FIX_DesigDetails.Desigid
AND LUP_EmpDesignation.Date=(SELECT TOP 1 LUP_EmpDesignation.Date
FROM LUP_EmpDesignation
WHERE EmployeeDetails.Empid=LUP_EmpDesignation.Empid
ORDER BY LUP_EmpDesignation.Date DESC)
INNER JOIN LUP_EmpProject
ON EmployeeDetails.Empid=LUP_EmpProject.Empid
AND LUP_EmpProject.StartDate=(SELECT TOP 1 LUP_EmpProject.StartDate
FROM LUP_EmpProject
WHERE EmployeeDetails.Empid=LUP_EmpProject.Empid
ORDER BY LUP_EmpProject.StartDate DESC)
INNER JOIN LUP_FIX_ProjectDetails
ON LUP_EmpProject.Projectid=LUP_FIX_ProjectDetails.Projectid
WHERE EmployeeDetails.Empid=1
PLEASE HELP.................
View 1 Replies
View Related
May 14, 2008
Hi,
I've running the below query for months ans suddenly today started getting the following error :"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
Any ideas as to why??
SELECT t0.DocNum, t0.Status, t0.ItemCode, t0.Warehouse, t0.OriginNum, t0.U_SOLineNo, ORDR.NumAtCard, ORDR.CardCode, OITM_1.U_Cultivar,
RDR1.U_Variety,
(SELECT OITM.U_Variety
FROM OWOR INNER JOIN
WOR1 ON OWOR.DocEntry = WOR1.DocEntry INNER JOIN
OITM INNER JOIN
OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod ON WOR1.ItemCode = OITM.ItemCode
WHERE (OITB.ItmsGrpNam = 'Basic Fruit') AND (OWOR.DocNum = t0.DocNum)) AS Expr1, OITM_1.U_Organisation, OITM_1.U_Commodity,
OITM_1.U_Pack, OITM_1.U_Grade, RDR1.U_SizeCount, OITM_1.U_InvCode, OITM_1.U_Brand, OITM_1.U_PalleBase, OITM_1.U_Crt_Pallet,
OITM_1.U_LabelType, RDR1.U_DEPOT, OITM_1.U_PLU, RDR1.U_Trgt_Mrkt, RDR1.U_Wrap_Type, ORDR.U_SCCode
FROM OWOR AS t0 INNER JOIN
ORDR ON t0.OriginNum = ORDR.DocNum INNER JOIN
RDR1 ON ORDR.DocEntry = RDR1.DocEntry AND t0.U_SOLineNo - 1 = RDR1.LineNum INNER JOIN
OITM AS OITM_1 ON t0.ItemCode = OITM_1.ItemCode
WHERE (t0.Status <> 'L')
Thanks
Jacquues
View 4 Replies
View Related
Jul 19, 2007
Hi guys,
A have a problem that I need understand.... I have 2 server with the same configuration...
SERVER01:
-----------------------------------------------------
Microsoft SQL Server 2000 - 8.00.2191 (Intel IA-64)
Mar 27 2006 11:51:52
Copyright (c) 1988-2003 Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
sp_dboption 'BB_XXXXX'
The following options are set:
-----------------------------------
trunc. log on chkpt.
auto create statistics
auto update statistics
********************************
SERVER02:
-----------------------------------------------------
Microsoft SQL Server 2000 - 8.00.2191 (Intel IA-64)
Mar 27 2006 11:51:52
Copyright (c) 1988-2003 Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
sp_dboption 'BB_XXXXX'
The following options are set:
-----------------------------------
trunc. log on chkpt.
auto create statistics
auto update statistics
OK, the problem is that if a run the below query in server01, i get error 512:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
But, if run the same query in the server02, the query work fine -.
I know that I can use IN, EXISTS, TOP, etc ... but I need understand this behavior.
Any idea WHY?
SELECT dbo.opf_saldo_ctb_opc_flx.dt_saldo,
dbo.opf_saldo_ctb_opc_flx.cd_indice_opf,
dbo.opf_saldo_ctb_opc_flx.cd_classificacao,
dbo.opf_movimento_operacao.ds_tipo_transacao ds_tipo_transacao_movimento ,
dbo.opf_header_operacao.ds_tipo_transacao ds_tipo_transacao_header,
'SD' ds_status_operacao,
dbo.opf_header_operacao.ds_tipo_opcao ,
dbo.opf_header_operacao.id_empresa,
dbo.opf_saldo_ctb_opc_flx.ic_empresa_cliente,
0 vl_entrada_compra_ctro ,0 vl_entrada_compra_premio,
0 vl_entrada_venda_ctro , 0 vl_entrada_venda_premio,
0 vl_saida_compra_ctro, 0 vl_saida_compra_premio,
0 vl_saida_venda_ctro, 0 vl_saida_venda_premio,
0 vl_lucro , 0 vl_prejuizo, 0 vl_naoexec_contrato,
0 vl_naoexec_premio,
sum(dbo.opf_saldo_ctb_opc_flx.vl_aprop_ganho) vl_aprop_ganho,
sum(dbo.opf_saldo_ctb_opc_flx.vl_aprop_perda) vl_aprop_perda,
sum(dbo.opf_saldo_ctb_opc_flx.vl_rever_ganho) vl_rever_ganho,
sum(dbo.opf_saldo_ctb_opc_flx.vl_rever_perda) vl_rever_perda,
sum(dbo.opf_saldo_ctb_opc_flx.vl_irrf) vl_irrf
FROM dbo.opf_saldo_ctb_opc_flx,
dbo.opf_header_operacao ,
dbo.opf_movimento_operacao
WHERE dbo.opf_saldo_ctb_opc_flx.dt_saldo = '6-29-2007 0:0:0.000'
and ( dbo.opf_header_operacao.no_contrato = dbo.opf_saldo_ctb_opc_flx.no_contrato )
and ( dbo.opf_header_operacao.no_contrato = dbo.opf_movimento_operacao.no_contrato )
and ( dbo.opf_movimento_operacao.dt_pregao = (select (o.dt_pregao) from dbo.opf_movimento_operacao o
where o.no_contrato = dbo.opf_movimento_operacao.no_contrato and o.dt_pregao <='6-28-2007 0:0:0.000' ) )
and (dbo.opf_saldo_ctb_opc_flx.ic_tipo_saldo = 'S')
group by dbo.opf_saldo_ctb_opc_flx.dt_saldo,
dbo.opf_saldo_ctb_opc_flx.cd_indice_opf,
dbo.opf_saldo_ctb_opc_flx.cd_classificacao,
dbo.opf_movimento_operacao.ds_tipo_transacao,
dbo.opf_header_operacao.ds_tipo_transacao ,
ds_status_operacao,
dbo.opf_header_operacao.ds_tipo_opcao ,
dbo.opf_header_operacao.id_empresa,
dbo.opf_saldo_ctb_opc_flx.ic_empresa_cliente
Thanks
Nilton Pinheiro
View 9 Replies
View Related
Jul 6, 2014
I am trying to add the results of both of these queries together:
The purpose of the first query is to find the number of nulls in the TimeZone column.
Query 1:
SELECT COUNT(*) - COUNT (TimeZone)
FROM tablename
The purpose of the second query is to find results in the AAST, AST, etc timezones.
Query 2:
SELECT COUNT (TimeZone)
FROM tablename
WHERE TimeZone NOT IN ('EST', 'MST', 'PST', 'CST')
Note: both queries produce a whole number with no decimals. Ran individually both queries produce accurate results. However, what I would like is one query which produced a single INT by adding both results together. For example, if Query 1 results to 5 and query 2 results to 10, I would like to see a single result of 15 as the output.
What I came up with (from research) is:
SELECT ((SELECT COUNT(*) - COUNT (TimeZone)
FROM tablename) + (SELECT COUNT (TimeZone)
FROM tablename
WHERE TimeZone NOT IN ('EST', 'MST', 'PST', 'CST'))
I get a msq 102, level 15, state 1 error.
I also tried
SELECT ((SELECT COUNT(*) - COUNT (TimeZone)
FROM tablename) + (SELECT COUNT (TimeZone)
FROM tablename
WHERE TimeZone NOT IN ('EST', 'MST', 'PST', 'CST')) as IVR_HI_n_AK_results
but I still get an error. For the exact details see:
[URL]
NOTE: the table in query 1 and query 2 are the same table. I am using T-SQL in SQL Server Management Studio 2008.
View 6 Replies
View Related
Feb 22, 2004
I am using a web page to enter records into a table that tracks production on machine parts.
I get two recordsets and loop through them using vbscript to get the totals.
I use two because I first get all production data greater than the last date an event occurred. The second I get the totals for the day of because I have to back out shifts of production prior to the event, the day of the event (ie 3 shift per day, 3rd shift begins the day so a day looks like this 3, 1, 2. We do an event on shift 1. I have to back out shift 3 as it happened prior to 1. Once I have the two seperate totals I then write a record in the historical data table with the event, shift, production totals, etc.
My question is can I get the production totals from within SQL or is looping through the rs's in vb better?
the vb for the shift is similar to this
If last_event_shift = 1 then
DayProd = shift1prod + shift2prod
elseif last_event_shift = 2 then
DayProd = shift2prod
elseif last_event_shift = 3 then
DayProd = shift1prod + shift2prod + shift3prod
else
end if
TotProd = DayProd + GreaterProd
Here is the SQL for each rs
Data Greater than last date
Select Sum(Production)AS TotProd, dbo.Production.LineNum, EventType
From dbo.Production INNER JOIN dbo.EventDate ON dbo.Production.LineNum = dbo.EventDate.LineNum AND dbo.Production.EntryDate > dbo.EventDate.EntryDate
Where dbo.EventDate.LineNum = @Line
Group By dbo.Production.LineNum, dbo.EventDate.EventType
Data for the last date
Select Max(dbo.EventDate.ShiftRemoved) AS RemovedShift, dbo.EventDate.Set_Pos, Max(dbo.EventDate.CutOff)AS CutOff, dbo.EventDate.EntryDate, Sum(Production)AS TotProd, dbo.Production.LineNum, EventType, Shift
From dbo.Production INNER JOIN dbo.EventDate ON dbo.Production.LineNum = dbo.EventDate.LineNum AND dbo.Production.EntryDate = dbo.EventDate.EntryDate
Where dbo.EventDate.LineNum = @Line
Group By dbo.Production.LineNum, dbo.EventDate.EventType, Shift, dbo.EventDate.EntryDate, dbo.EventDate.Set_Pos
Thanks in advance,
Lee
View 2 Replies
View Related
Mar 16, 2007
Hello All,
I have done a report that shows all the subtotals however, I want to show the grand total (the sum of each subtotal) in a row. I am using SQL server BI studio-2005. I know I can add a row but all the rows are detailed rows and subsequenlty reflect the subtotals for last record in the report. All I need to know what type of row do I need to add to show my totals.
Thanks,
Rashi
View 3 Replies
View Related
Feb 4, 2002
This is probably a simple task but I just don't know how to do it. I need to return a recordset of details with a row of totals for selected columns. Something with a result like this:
Location Attendance Showings
======== ========== ========
JOHNS 210 3
SEREN 116 2
total 326 5
I know I could do this with a stored procedure, but I'd prefer to do it with just one sql statement. I tried compute but because I have a total on more than one column, the returned recordset is actually 3 rows.
Thanks in advance for any suggestions.
View 2 Replies
View Related
Oct 1, 1999
I have a situation where I want to get running totals of a potentionally very large table. Say I have a million records with a table with few fields.
Table structure like this
UID value
1 3
2 9
3 4
4 7
5 2
I want to return a result set of something like this
select uid, value, (rtotal???) from table
uid value rtotal
1 3 3
2 9 12
3 4 16
4 7 23
5 2 25
This is to be used for sort of a lotery. Say I have 1 million users with a variety of points tward the lotery. I total the points, is say 5 million, determined
the winner to be say 3,234,563 Now I have to determine which uid is the winner. So I planned to to do a running total till the winning value
is less then or equal to the running total and I have my winner. I am looking for a fast way to do this on a large database.
Any Ideas?
View 1 Replies
View Related
May 27, 2002
--Select Capital_Amount + Interest_Amount + Insurance_Amount + Admin_Fee
--from Loan Where loan_no = '9110001AA667'
--Select top 3* from loan
Select sum(Capital_Amount) As Capital_Amount from Sales
Select * from Sales
How can l run these two Queries in the same view. l want to display what l have in the salesNew View and at the same time sum all the amount columns.But l'm not
being successful. Is it achievable or l have to have two separate views?
CREATE View SalesNew
AS
SELECT DISTINCT
tr.Transaction_Date,
tr.Loan_No,
n.Store,
n.User_Issued,
n.LoanBook As Company,
p.Product,
n.Capital_Amount,
n.Interest_Amount,
n.Insurance_Amount,
n.Admin_Fee,
n.Total_Amount
FROM Transaction_Record tr
INNER JOIN Loan n
ON tr.loan_No = n.loan_No AND tr.loan_No = n.loan_No
INNER JOIN Product p ON n.product = p.product
--2nd query
Select n.loanbook As Company,Sum(n.Capital_Amount) As Capital_Amount,
Sum(n.Interest_Amount) As Interest_Amount,
Sum(n.Insurance_Amount) As Insurance_Amount,
Sum(n.Admin_Fee) As Admin_Fee,
Sum(n.Total_Amount) As Total_Amount
From Loan n
Group By n.loanBook with RollUp
View 2 Replies
View Related
Jan 12, 2004
Hi Folks,
I have a problem that I know that i should be able to code up but have drawn a blank due to it being monday. Anyway......
Have a table :
create table test_registrations
(
date_maint smalldatetime,
user_name1 varchar (255),
user_address1 varchar (255),
total_users int
)
go
If i have a number of registrations on a particular date then I can tell all how many users have registered in any date by :
select date_maint , count (1)
from test_registrations
group by date_maint
order by date_maint desc
go
The qestion is how can I keep a total registared users count. Say if I have 10 users join on the 1st of Jan and 15 on the 3rd then I want
the total users for the users on 1st to read 10 and total users on the 3rd to read 25.
I know i should be able to code this up but I'm being a dumb ass. Can someone show me a way to code it. Is it some sort of correlated sub query to keep a running total ?
View 3 Replies
View Related
May 23, 2008
On SQL Server 2005 at least, this works efficiently where we have an indexed row number.
It does seem to be very sensitive to the join condition in the recursive part of the CTE: changing it to the equivalent "ON T.rn - 1 = RT.rn" results in a scan of T each time instead of a seek!
DROP TABLE dbo.T
-- rn must have contiguous values for this to work:
CREATE TABLE dbo.T (rn int PRIMARY KEY, f float NOT NULL)
-- 100000 random floats between 0 and 1:
INSERT INTO dbo.T
SELECT n+1 AS rn, RAND(CAST(NEWID() AS binary(4))) AS f
FROM dbo.Numbers
GO
;WITH RT AS (
SELECT rn, f AS rt
FROM dbo.T
WHERE rn = 1
UNION ALL
SELECT T.rn, RT.rt + T.f
FROM RT
INNER JOIN dbo.T AS T
ON T.rn = RT.rn + 1
)
SELECT *
INTO dbo.TRT
FROM RT
--ORDER BY rn
OPTION (MAXRECURSION 0)
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 1 ms.
Table 'Worktable'. Scan count 2, logical reads 600001, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'T'. Scan count 100000, logical reads 200002, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
SQL Server Execution Times:
CPU time = 3500 ms, elapsed time = 3724 ms.
(100000 row(s) affected)
View 4 Replies
View Related
Jun 11, 2008
Now my code below brings everything i want it too, the problems comes is I need to get a running total of sales for each day. Currently it shows the sales for a store for each day and what there projections should be. I need a running total for each day so if you were to have todays date it would have the sum(sales) between today and the first or the month that im in. but still show what the total was on the 10th, 9th, and so on.
Declare @Brand as varchar(10)
DECLARE @StartDate datetime
Declare @EndDAte as Datetime
Set @Brand = 'business'
SELECT @StartDate=CAST('1/1/'+CAST(YEAR(GETDATE()) AS varchar(4)) AS datetime)
SET @EndDate =CAST('12/31/'+CAST(YEAR(GETDATE()) AS varchar(4)) AS datetime)
Select ttProjection.StoreID,S.StoreName , ttProjection.DailyProjection, ttProjection.DAYS, ISNULL(ttSales.Sales,0) as Sales
From
/**********Finds projection per day****************/
(Select StoreID, Projection, Projection/Cast(DaysInMonth as INT) as DailyProjection, DAYS
From
(Select StoreID, Projection as Projection,
Month, Day(DateAdd(m, 1,DateAdd(d,1 - Day(Month), Month))-1) As DaysInMonth
From Reporting.dbo.RetailSalesComparison_ProjectionsView
Where StoreID between 12000 and 12999
)ttTemp
Right Join
(SELECT DATEADD(dd,number,@StartDate) as DAYS
FROM
(
select number from master..spt_values
WHERE type='p'
union all
select number+256 from master..spt_values
WHERE type='p'
) as s
where DATEADD(dd,number,@StartDate)<=@EndDate)ttDays on Month(ttTemp.Month) = Month(ttDays.DAYS))ttProjection
Left Join
(Select Date, StoreID, Sum(Sales) as Sales
From Reporting.dbo.RetailSales_byStore_byDay
Group By Date, StoreID)ttSales
on ttProjection.StoreID = ttSales.StoreID
and ttProjection.DAYS = ttSales.Date
Inner Join DelSolNet2.dbo.Store S on ttProjection.StoreID = S.StoreID
Where Month(Days) = Month(getdate())
Order By Days, ttProjection.StoreID
View 3 Replies
View Related
Nov 14, 2006
I am relatively new to SQL i.e. I know the basics!
What I am trying to do is: I have a database of customer spend and I am trying to segment them into certain %ages of the search results. So, for example, find all of the customers that are in the top 10% of spenders (I also want to only select customers with a spend of greater than x!). I am trying to do this using a Case When but feel that I may be out of my depth.
Please help if you can!!
Thanks, Kris
View 4 Replies
View Related
Aug 25, 2006
I have a tblTax. It has fields InvoiceNum, TaxAuthority, TaxableTotal,NonTaxableTotal, TaxCollected.Sample data1,county,10.00,0.00,0.401,city,10.00,0.00,0.102,state,0.00,15.00,0.15When totaling invoice 1 should have totals of 10.00,0.00,0.50 becausethe 10.00 is the total for the invoice, but 0.50 is the total taxcollected. I nee these totals in a report. In crystal reports i couldjust do a total on change of invoice number for the Taxable andnonTaxable Totals. but i have to this on an Access adp. I was hoping icould get a query to return something likeinv,auth,Taxable,nonTaxable,Collected,TaxableTot,N onTaxableTot,CollectedTot1,county,10.00,0.00,0.40,10.00,0.00,0.501,city,10.00,0.00,0.10,10.00,0.00,0.502,state,0.00,15.00,0.15,0.00,15.00,0.15I'm not sure how to do a group by that would allow this, although imsure its possible.
View 3 Replies
View Related
Dec 29, 2006
Hi,Am using robvolks crosstab-procedure to generate a crosstab query.I get this result:Total A B Cjuli 455 1 107 347okt 83 1 9 73aug 612 1 113 498juni 451 1 108 342So I get a total for each month. But I would also like a total of eachletterTotal A B Cjuli 455 1 107 347okt 83 1 9 73aug 612 1 113 498juni 451 1 108 342Total 1601 4 337 1260Is that possible?/jim---call to procedureexecute crosstab 'select DATENAME(month,(theDate)) as '' '', count(*) as'MonthsTotal'' from tblData group byDATENAME(month,(theDate))','count(letter)','letter ','tblData'-----------Robvolks procedure----CREATE PROCEDURE crosstab@select varchar(8000),@sumfunc varchar(100),@pivot varchar(100),@table varchar(100),@where varchar(1000)='1=1'ASDECLARE @sql varchar(8000), @delim varchar(1)SET NOCOUNT ONSET ANSI_WARNINGS OFFSET LANGUAGE DanishEXEC ('SELECT ' + @pivot + ' AS pivot INTO ##pivot FROM ' + @table + ' WHERE1=2')EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table +' WHERE '+ @where + ' AND ' + @pivot + ' Is Not Null')SELECT @sql='', @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date',data_type) )WHEN 0 THEN '' ELSE '''' ENDFROM tempdb.information_schema.columnsWHERE table_name='##pivot' AND column_name='pivot'SELECT @sql=@sql + '''' + convert(varchar(100), pivot) + ''' = ' +stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN '+ @delim + convert(varchar(100), pivot) + @delim + ' THEN ' ) + ', ' FROM##pivotDROP TABLE ##pivotSELECT @sql=left(@sql, len(@sql)-1)SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql+ ' ')EXEC (@select)SET ANSI_WARNINGS ONGO
View 3 Replies
View Related
Dec 8, 2007
How can I return daily running totals for each day:
TABLE:
date: # of downloads
1/1/2007 100
1/1/2007 12
1/1/2007 8
1/2/2007 100
1/2/2007 20
1/2/2007 20
1/3/2007 40
example of what I want:
RESULTS:
date number of downloads total
1/1/2007 120 120
1/2/2007 140 260
1/3/2007 40 300
I want to return a running total value for each seperate day.
View 4 Replies
View Related
Mar 20, 2008
I'm writing reports that absolutely require page totals for several columns. I don't need a cumulative total for everything in the report, just for the items on the current page. Is this doable in SSRS? If not, is there another reporting package that supports putting data in the header or footer?
View 3 Replies
View Related
Feb 4, 2008
I have a report, using a table, that is grouped by acct. The acct indicates either revenue or expenses. I have a total in my table that will give me the totals for revenue, and the total for expenses. At the end of the report, in the table footer, I want to add a Surplus/Deficit total, which would be the total revenue - total expenses, but I can't seem to get it right. I tried the following:
=Sum(ReportItems!table1_Group1.Value)
thinking that it would give me the total by the group, but I get the error that an aggregate function can only be used on page header and footer. How do I just get a basic grand total in my report?
Thanks in advance!
View 1 Replies
View Related
Dec 12, 2006
Below is part of a matrix report. Sooo close, but I have two problems I have not been able to solve. Please help as a I have several similar reports to do.
1. Row totals. I have been able to get a row total by adding a row group (i.e., $849.7 in the first row). However it does not display a group total (i.e., the sum of $849.7 and $371.3 for Economic Development) for that column.
I have not been able to add a static column outside of the dynamic groupings. I thought this might be a resolution by displaying the sum of the Estimated Costs in a static column and hoping it would show the group totals the same as with the dynamic column totals. Is there a way to do this?
2. Sorting. The report needs to display the groups based on the descending total values. I have specified the following sorts on the groups: sum(Fields!Estimated_Cost),"matrix1_Proj_Typ_Group" descending (this is the first column) and sum(Fields!Estimated_Cost),"matrix1_Proj_Typ" descending (this is the second column). Neither sort appears to be work.
City
County
Federal
Joint
Estimated Cost
% of Total
Estimated Cost
% of Total
Estimated Cost
% of Total
Estimated Cost
% of Total
Economic Development
Business District Development
$849.7
$816.0
66.83%
$27.2
2.23%
$0.0
0.0%
$6.5
0.53%
Industrial Sites & Parks
$371.3
$131.5
10.77%
$190.4
15.59%
$0.0
0.0%
$36.0
2.95%
Total
$947.6
77.61%
$217.6
17.82%
$0.0
0.0%
$42.5
3.48%
Education
K-12 New School Construction
$1,594.7
$223.0
10.05%
$1,363.5
61.43%
$0.0
0.0%
$0.0
0.0%
Non K-12 Education
$37.8
$3.1
0.14%
$33.2
1.5%
$0.0
0.0%
$0.0
0.0%
School System-wide Need
$587.1
$167.2
7.53%
$419.2
18.89%
$0.0
0.0%
$0.0
0.0%
Total
$393.2
17.72%
$1,816.0
81.82%
$0.0
0.0%
$0.0
0.0%
General Government
Other Facilities
$21.3
$17.5
4.3%
$3.9
0.95%
$0.0
0.0%
$0.0
0.0%
Property Acquisition
$8.8
$6.8
1.68%
$2.0
0.49%
$0.0
0.0%
$0.0
0.0%
Public Buildings
$375.5
$294.2
72.54%
$72.0
17.74%
$3.0
0.74%
$6.2
1.52%
Total
$318.5
78.52%
$77.8
19.19%
$3.0
0.74%
$6.2
1.52%
View 4 Replies
View Related
May 2, 2007
Hi Everyone I have an ADP and I need to create a report that will give me the total number of each item. I need the report to show how many [Violation Type], and the total [Loss] per violation. Can anyone help please
Code Snippet
CREATE TABLE [dbo].[Revised_MainTable] (
[I/RDocument] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[IR Number] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date] [datetime] NULL ,
[Inspector] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Area] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Violation] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Violation Type] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Loss] [money] NULL ,
[Loss Type] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Employee] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Guest] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Action] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Action Type] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Notes] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Security/GC] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
View 9 Replies
View Related
Feb 12, 2008
I have a matrix that displays the number of employees grouped by their grade and department and business group. At the bottom i have a subtotal cell displaying total like so for each group
Accounts admin assistant engineer
BSG CENBUS 1 0 0
CENFIN 1 1 0
SUB TOTAL 2 1 0
BUILDINGS BIRST1 0 1 1
CHBRS1 0 1 1
SUB TOTAL 0 2 2
what i need is a total of all employees in each grade as well at the bottom of the matrix like so
Accounts admin assistant engineer
BSG CENBUS 1 0 0
CENFIN 1 1 0
SUB TOTAL 2 1 0
BUILDINGS BIRST1 0 1 1
CHBRS1 0 1 1
SUB TOTAL 0 2 2
TOTAL 2 3 2
Is there a way i can add another row below the subtotals that only appears at the bottom and that sums either the subtotals together or the entire columns?
View 1 Replies
View Related
Nov 15, 2007
Hi,
I have a report which shows data such like this
Date
Description
Debit Amount
Credit Amount
Tax
Balance
31-Dec-9999
CHARGE
197.3600
0.0000
11.8400
11.8400
23-Jun-1992
PAYMENT
12.0000
209.2000
10.0000
12.890
22-Jun-1992
CHARGE
157.3600
0.0000
15.1600
17.8400
I put a detail group on the report for this output.
I wanted to add a summary at the end of the report. which will show me the total according to filter like (if i add group footer it shows sum for all description and only in grouped row but i wanted to show total at the end and only desired groups) Here is an example.
I also had created a calculated filed to calculate totals =IIF( Fields!AccountClass.Value="CHRGE", Fields!SalesTax.Value,0)
it works fine but when i try to "sum" this filed it shows error instead of result.
Tax (for charge) = 17.00
Tax (for payment) = 10.00
i have a lot of descriptions but wanted to show the sum of only given descriptions.
If anyone know about it please inform me. I am new to Sql server reporting.
thanks in advance
View 4 Replies
View Related
Jan 19, 2007
We are trying to create a report that shows a Week to Date, Month to Date, and Year to Date
Week to Date Month to Date Year to Date
Item Number
I've tried using an if statement (if date = current week, Qty, 0) and then sum the data but I get an error message that reportitems can only be summed in the page header and footer. I've also tried running totals, but it doesn't like the iif statement. Any ideas on how to do this?
Nancy
View 6 Replies
View Related
Nov 14, 2007
Hi,
Is there a way to display the sum of a group of a field?
I've created a group, but when I put the expression of SUM(Field) in the group footer, it gives me the total of Field for the whole dataset.
Is there a way I can display the just the Totals of the Groups?
so if my data looks like :
a | 1
a | 2
a | 3
b | 4
b | 5
b | 6
I want to display :
a | 1
a | 2
a | 3
Total a | 6
b | 4
b | 5
b | 6
Total b | 15
but instead, when i add the SUM expression into the footer group, I get :
a | 1
a | 2
a | 3
Total a | 21
b | 4
b | 5
b | 6
Total b | 21
View 8 Replies
View Related
Aug 20, 2007
I have a db that tracks clients, payments, and clients codes. A client can be assigned many codes. In my query I'm asking to see any clients that have two selected codes and also of those show me those that have a sum of payments between 1 and 100000 dollars. The query returnes the clients with the selected codes, but the total payments is multiplied by the number of the codes they have of the ones that I select. In this case 'email group' or 'member'
So if a client had a total of $20,000 dollars in payments and they had both of the codes I selected the sum of payments is returned as $40,000.
Any thoughts are appreciated!
Here is a sample example:
SELECT DISTINCT [Salutation], [Client_ID] AS 'Client ID', SUM([dbo].[vw_ClientTotals].[Total Payments]) AS 'Sum(Total Payments)'FROM [dbo].[All_Constituents]INNER JOIN [dbo].[tblClientCodes] ON [dbo].[tblClientCodes].[Client_ID]=[dbo].[All_Constituents].[Client_ID]INNER JOIN [dbo].[tblClientCodeLookUp] ON [dbo].[tblClientCodeLookUp].[ClientCode_ID]=[dbo].[tblClientCodes].[ClientCodeLookup_ID]INNER JOIN [dbo].[vw_ClientGiftTotals] ON [dbo].[vw_ClientGiftTotals].[Client_ID]=[dbo].[All_Constituents].[Client_ID]WHERE ( ([dbo].[tblClientCodeLookUp].[ClientCode] = 'Member') OR ([dbo].[tblClientCodeLookUp].[ClientCode] = 'Email Groups') )GROUP BY [dbo].[All_Constituents].[Salutation], [dbo].[All_Constituents].[Client_ID]HAVING (SUM([dbo].[vw_ClientTotals].[TotalPayments]) BETWEEN '1' AND '100000')
View 6 Replies
View Related
Feb 26, 2008
Been trying to wrap my head around this one, I'm sure its quite possible but can't figure it.I've got a massive table of Items, each of which has a category. I want to bring back a list of categories and a total number of items in each category, so a result set which would look like:Category NoOfItemsInCategory--------------------------------------------------Category1 15Category2 1287Category3 25How would I write this query? I've been messing around with Group By and Distinct but can't get the effect I'm wanting.Thanks!
View 1 Replies
View Related
May 23, 2014
I have the following code which essentially lists the total sales for an items on the first row, and the total credits for the same item on the second row.
Code:
SELECT T0.ItemCode, SUM(T0.LineTotal) as 'Total Sales'
FROM INV1 T0
WHERE T0.ItemCode = 'ACR2401010'
GROUP BY T0.ItemCode
[code]...
What I would like to do is write a code block that subtracts the total credits from the total sales, leaving me with only one row of data for the ItemCode.
View 7 Replies
View Related