SQL Group By With Multiple Sums?
Feb 27, 2008
I am creating a statistics page for our site. Using a very basic select statement, my query currently returns:
Select DateAdded, MTCreds, HICreds from tblStudentsAndCredits
DateAdded-MTCreds-HICreds
-----------------------------------------
1/1/2008 - 2 - 0
1/1/2008 - 0 - 4
1/2/2008 - 3 - 0
1/2/2008 - 2 - 4
1/3/2008 - 2 - 0
1/3/2008 - 0 - 3
Instead, I would like it sum up MTCreds and HICreds for each day and group them into something more usable like this:
DateAdded-MTCreds-HICreds
-----------------------------------------
1/1/2008 - 2 - 4
1/2/2008 - 5 - 4
1/3/2008 - 2 - 3
Thanks for any help - SQL is not my strong point.
View 3 Replies
ADVERTISEMENT
May 13, 2008
Hello All,
I'm trying to do a query to produce multiple sums based on how many rows are in a table.
Here's a sample of the table and data, what I want is to have a query to sum each company's total and display it.
create table #invoices
(
InvoiceNumber varchar(5),
--other info
CompanyCode int,
InvoiceAmount real
)
Insert Into #invoices values('A1000', 1, 1000)
Insert Into #invoices values('A1000', 2, 100)
Insert Into #invoices values('A1000', 3, 300)
Insert Into #invoices values('A1000', 1, 600)
Insert Into #invoices values('A1001', 2, 2000)
Insert Into #invoices values('A1001', 3, 1000)
Insert Into #invoices values('A1001', 1, 300)
Insert Into #invoices values('A1002', 2, 2500)
Insert Into #invoices values('A1002', 3, 2000
I was thinking of doing it something like this:
Select
Sum(case when CompanyCode=1 Then CompanyCode End) as TOTAL1,
Sum(case when CompanyCode=2 Then CompanyCode End) as TOTAL2,
Sum(case when CompanyCode=3 Then CompanyCode End) as TOTAL3
from
#invoices
But I would rather not have to hard code the company numbers in the query as they can be added or removed from the list. Ideally it would take the CompanyCode from the COMPANY table and SUM each companies totals and display it.
Any help on this would be greatly appreciated!
Thanks,
View 3 Replies
View Related
Apr 12, 2007
Hello All
I am trying to figure out if what i am attempting to do is possible and whether or not my approach is wrong to begin with.
I am trying to build a custom report for our accounting system which is Traverse from Open systems. This is what i have done in the stored procedure thus far
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER PROCEDURE rptArFLSalesByCustItemized_sp
@custId pCustID,
@dateFrom datetime,
@dateThru datetime,
@itemIdFrom pItemId,
@itemIdThru pItemId
as
set nocount on
-- define some variables for previous year
declare @LYqty int, @LyAmt money, @LYfrom datetime, @LYthru datetime
-- set defaults
SET @itemIdFrom=ISNULL(@itemIdFrom,(SELECT MIN(itemId) FROM tblInItem))
SET @itemIdThru=ISNULL(@itemIdThru,(SELECT MAX(itemId) FROM tblInItem))
SET @LYfrom=DATEADD(YEAR,-1,@dateFrom)
SET @LYthru=DATEADD(YEAR, -1, @dateThru)
-- create small temp table to hold customer info
Create Table #tmpArCustInfo
(
custId pCustID,
custName VARCHAR (30),
)
-- populate customer temp table with info
Insert into #tmpArCustInfo
select custId, custName
from tblArCust
WHERE custId = @custId
-- create a temp table to hold the Data for each Item
Create Table #tmpArSalesItemized
(
itemId pItemId,
productLine VARCHAR (12),
pLineDesc VARCHAR (35),
descr VARCHAR (35),
LYQtySold int,
LYTDQtySold int,
QtySold int,
LYTDsales money,
totalSales money,
LastInvDate datetime,
)
-- populate the temp table with all of the inventory items
insert into #tmpArSalesItemized
select ii.itemId, ii.productLine, ip.Descr, ii.Descr, 0,0,0,0,0, NULL
from tblInItem ii, tblInProductLine ip
where ip.productLine = ii.productLine
AND ii.itemId BETWEEN @itemIdFrom AND @itemIdThru
-- update table with this years quantities
update #tmpArSalesItemized
SET QtySold = (select SUM(QtyOrdSell) from tblArHistDetail hd
where TransId IN (select TransId from tblArHistHeader where custId = @custId)
AND orderDate IN (select OrderDate from tblArHistHeader where OrderDate BETWEEN @dateFrom AND @dateThru)
AND hd.partId BETWEEN @itemIdFrom AND @itemIdThru
GROUP BY hd.partId
)
-- Return the temp tables results
select * from #tmpArSalesItemized, #tmpArCustInfo
drop table #tmpArSalesItemized, #tmpArCustInfo
return
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
My problems begin where i want to start updating all of the Qty's of the QtySold field. I have managed to get it to write the same sum in every field but i cannot figure out how to update each row based on the sum of the qty found for that item in the tblArHistDetails table, trouble is too that there is no reference to the custId in that table either. The custId resides in tblArHistHeader and is linked to the details table via the TransId column. So really i need to update many rows based on criteria from 2 other tables.
Can anyone please help? I dont have a clue how to make this work, and most of what i have learned about sql thus far has been from opening other stored procs etc in the accounting system and just reading to see how the developers have done things.
Thanks
Jamie
View 1 Replies
View Related
May 19, 2015
partition with single file group or multiple file group which one best.
we have some report running from partition table, few reports don't have any partition Key and after creating 400 partition with 400 file group it is slow.what is best practices to crate 400 file group or single file group.
View 9 Replies
View Related
Oct 19, 2005
Hello, any help is appreciated.Here is what I’m trying. I want a month to date total of bookingsbased on a fiscal month.I can isolate my records for the month and sum up the days so I windup with a list of days of the month with their bookings total forthat day. Like this10/1/05 - $100010/2/05 - $500010/3/05 - $2000And so on thru the month.But I want the sum of month 10.I have a line of code like “select sum(EXT_AMT) where month = “10””What I need is sum(sum(EXT_AMT).And that does not work.Any suggestions? I thought to throw the results into a table then sumthe table.Not sure how to do that either! I'm frustrated! Any help isappreciated.Thanks, Duane
View 2 Replies
View Related
Jan 31, 2007
hi,
i would like to know how to perform more than 1 group by in one SELECT. reason is i need to group by 1-to calculate totalx, and perform subgroup to calculate totalq. Say, this is the eg :-
From DB
storageid originqty cartonid
P00110C001
P00110C002
P0015C003
P00220
Result
Storageid TotalCtnInPalletTotalCartonPcsInCarton
P0013210
P001315
P0020020
*TotalCtnInPallet = Total of cartonID contain in 1 storageid
*TotalCarton = Total cartonID that has same OriginQty
*PcsInCarton = OriginQty
thanks.. ive tried this using nested select but the result very slow.. like my other topic- temp table or nested select..
so id like to know second opinion to achieve this group by calcualation.. thankss
~~~Focus on problem, not solution~~~
View 3 Replies
View Related
Jul 29, 2004
I have this query:
select Customers.CustomersID, Customers.name, sum(table1.amount), sum(table2.amount)
from Customers, table1, table2
where Customers.CustomerID = table1.CustomerID
and Customers.CustomersID = table2.CustomerID
group by Customers.CustomersID, Customers.name
I am trying to make a query to report the total amount of two different things from two different tables by customer. the problem is that the total amount from table1 doubles if there are two rows of that customer in table2. My guess is that I have to group the things in a different way, but I don't know how.
Any suggestions?
View 1 Replies
View Related
Feb 21, 2008
Ok I have two tables
clients and expenses
enpense table columns: clientid, expensetype, expensevalue
clients.clientid and expenses.clientid relate the tow tables on an inner join
what i have is one client that will have multiple expense records in the expense table
cleint1, expensetype1, expensevalue1
cleint1, expensetype2, expensevalue2
cleint1, expensetype3, expensevalue3
what i need to output is client.*, sum(expensevalues), and also expensevalue1, expensevalue2, expensevalue3 as one output line
how do I get this?
View 3 Replies
View Related
Jul 23, 2005
Hi AllI'm really stuck on this one so would appreciate any help you can give.In essence, I have 1 SQL 2000 table with rows of data logging stockmovement. To differenciate between a stock sale and a stock receipt thetable has a TRANSACTIONTYPE field so that 8,7 equal invoices and 3 equals areceipt.I've been asked to report on this data by suming the total qty used oninvoices and the total qty recvd for each stock item, but I can't figure outhow I sum the same rows twice in the one query.For example, my query is as follows:select st.stockid as 'STYLE',s.picture as 'COLOUR','' as 'IN FIRST IN LAST WEEK','' as 'THIS WEEK IN','' as 'TOTAL IN','' as 'OUT FIRST OUT LAST WEEK',SUM(st.quantity) as 'THIS WEEK OUT','' as 'TOTAL OUT','' as 'REMAINING','' as 'TOTAL DIGESTION %'from stocktransactions st, stock swhere st.stockid = s.stockid andst.transactiontype in (8,7) andst.transactiondate >= '2005-07-12 00:00:00' andst.transactiondate <= '2005-07-12 23:59:59'group by st.stockid,s.pictureorder by st.stockidApart from the 'THIS WEEK OUT' column SUMing all of the stock sales bytransactiontype 7,8, I also want the 'THIS WEEK IN' column to SUM all of thetransactions by transactiontype 3, so that I get the following results:STYLE COLOUR .... THIS WEEK IN .... THIS WEEK OUT .......IVP Red 12 23STP Blue 4 15etc etcMy problem is that I don't want to exclude a stock item if it hasn't got arow/value for the THIS WEEK IN and/or the THIS WEEK OUT. Am I asking toomuch of SQL?My table schemas are as follows:create table STOCKTRANSACTIONS(STOCKTRANSACTIONID T_STOCKTRANSACTIONSDOMAIN not nullidentity(1,1),TRANSACTIONTYPE smallint not null,TRANSACTIONDATE datetime null ,REFERENCE varchar(40) null ,Comment varchar(255) null ,STOCKID T_STOCKDOMAIN null ,DESCRIPTION varchar(255) null ,UNITOFSALE varchar(20) null ,WAREHOUSEID T_WAREHOUSESDOMAIN null ,PEOPLEID T_PEOPLEDOMAIN null ,AccountID T_AccountsDomain null ,AgentID T_AgentsDomain null ,PLRate float null ,CONTACTID T_CONTACTDETAILSDOMAIN null ,JOBID T_JOBSDOMAIN null ,QUANTITY float null ,CURRENCYID T_CURRENCIESDOMAIN null ,SELLINGPRICE float null ,DISCOUNTPERCENT float null ,COSTPRICE float null ,MINIMUMPRICE float null ,TILLID T_TILLSDOMAIN null ,UserID T_UsersDomain null ,ClockDate DateTime null ,TimeStamp TimeStamp ,constraint pk_stocktransactions primary key (STOCKTRANSACTIONID))gocreate table STOCK(STOCKID T_STOCKDOMAIN not null,NAME varchar(40) not null,PICTURE varchar(40) null ,WEIGHT float null ,VOLUME float null ,BARCODE smallint null ,NumberOfPriceBreaks SmallInt not null default 1,STOCKCATEGORYID T_STOCKCATEGORIESDOMAIN null ,SALESNOMINALID T_NOMINALACCOUNTSDOMAIN null ,PURCHASENOMINALID T_NOMINALACCOUNTSDOMAIN null ,SELLINGCOMMENT varchar(255) null ,INCLUDESELLINGCOMMENT TinyInt null ,DISPLAYSELLINGCOMMENT TinyInt null ,COSTCOMMENT varchar(255) null ,DISPLAYCOSTCOMMENT TinyInt null ,PRODUCTTRACKING smallint null ,ITEMTYPE smallint null ,VALUATIONPRICE float not null default0.00 ,INCLUDEINCUSTOMERSTURNOVER TinyInt null ,INCLUDEINAGENTSTURNOVER TinyInt null ,SUPERCEDED TinyInt null ,SUPERCEDEDBY T_STOCKDOMAIN null ,SUPPLIERID T_PEOPLEDOMAIN null ,SUPPLIERSTOCKID varchar(40) null ,SUPPLIERCOMMENT varchar(255) null ,NEXTSERIALNUMBER int null ,SERIALNUMBERLENGTH smallint null ,SERIALNUMBERPREFIX varchar(10) null ,SERIALNUMBERSUFFIX varchar(10) null ,SERIALNUMBERPREFIXLENGTH smallint null ,SERIALNUMBERSUFFIXLENGTH smallint null ,TIMESTAMP timestamp not null,constraint pk_stock primary key (STOCKID))goThanksRobbie
View 3 Replies
View Related
May 12, 2006
Could someone explain to me, how I can get sum from row which I have values in 2 colums and I want the realtime sum to third column. Fourth colum is for item.
Also can someone tell me how to sum these third colums where the item is same so I have real time values for the item sum.
Thanks!
AD
View 1 Replies
View Related
May 5, 2006
How can I combine the 2 Sum amounts below. Basically teh 2 queries are exactly the same, just hitting 2 different tables (pdc and pdcdeleted) with the same structure:
SELECT SUM(PQuery.Amount) as PDCs_IL
FROM
(SELECT c.name,
c.customer,
(SELECT Top 1 fd.Fee1 FROM FeeScheduleDetails fd
where c.feeSchedule = fd.code)
AS FeeSchedule,
m.branch,
pd.desk,
'PDC' AS Type,
pd.Active,
m.number,
pd.Amount,
CONVERT(money, 0) AS OverPaidAmt,
pd.OnHold
FROM Master m (NOLOCK)
LEFT JOIN pdc pd ON pd.number = m.number
INNER JOIN Customer c ON c.Customer = m.Customer
WHERE pd.Active = 1
AND m.Customer IN (SELECT Customer from Customer_DashboardGraphs where Illinois = 1)
AND pd.Entered BETWEEN DATEADD(DAY, -DATEPART(DAY, @ProcessDate) + 1, @ProcessDate) AND DATEADD(DAY, -DATEPART(DAY, @ProcessDate), DATEADD(MONTH, 1, @ProcessDate)) AND pd.Entered <> '1900-01-01 00:00:00.000'
AND pd.Deposit BETWEEN DATEADD(DAY, -DATEPART(DAY, @ProcessDate) + 1, @ProcessDate) AND DATEADD(DAY, -DATEPART(DAY, @ProcessDate), DATEADD(MONTH, 1, @ProcessDate))
AND pd.Deposit IS NOT NULL
AND pd.OnHold IS NULL
AND c.customer <> '9999999'
) as PQuery
SELECT SUM(PQuery2.Amount) as PDCs_IL_deleted
FROM
(SELECT c.name,
c.customer,
(SELECT Top 1 fd.Fee1 FROM FeeScheduleDetails fd
where c.feeSchedule = fd.code)
AS FeeSchedule,
m.branch,
pd.desk,
'PDC' AS Type,
pd.Active,
m.number,
pd.Amount,
CONVERT(money, 0) AS OverPaidAmt,
pd.OnHold
FROM Master m (NOLOCK)
LEFT JOIN pdcdeleted pd ON pd.number = m.number
INNER JOIN Customer c ON c.Customer = m.Customer
WHERE pd.Active = 1
AND m.Customer IN (SELECT Customer from Customer_DashboardGraphs where Illinois = 1)
AND pd.Entered BETWEEN DATEADD(DAY, -DATEPART(DAY, @ProcessDate) + 1, @ProcessDate) AND DATEADD(DAY, -DATEPART(DAY, @ProcessDate), DATEADD(MONTH, 1, @ProcessDate)) AND pd.Entered <> '1900-01-01 00:00:00.000'
AND pd.Deposit BETWEEN DATEADD(DAY, -DATEPART(DAY, @ProcessDate) + 1, @ProcessDate) AND DATEADD(DAY, -DATEPART(DAY, @ProcessDate), DATEADD(MONTH, 1, @ProcessDate))
AND pd.Deposit IS NOT NULL
AND pd.OnHold IS NULL
AND c.customer <> '9999999'
) as PQuery2
View 1 Replies
View Related
Jun 20, 2012
creating a query to group identical rows into one and placing corresponding data in appropriate columns for a table named items, what I mean is that I have a table structured as below
Itemcode, Description, Period1, Period2, Period3
001--------Desc--------233,---------,------- <<ROW1
001--------Desc ------------ ,100,------------ <<ROW2
001--------Desc ------,--------,-------,300 <<ROW3
Row one contains a value in Period1
Row two contains a value in Period 2
Row three contains a value in Period 3
I need to create a query so that the end result would look like this;
Itemcode, Description, Period1, Period2, Period3
001 --------Desc -------233 ----100 ---300
creating an sql query to get the above result?
View 2 Replies
View Related
May 30, 2008
eg say.
i have a table emp
data
----
id name phone no
1 smith 423-422-5226
1 smith 414-255-5252
2 george 511-522-2525
2 george 524-522-2428
........
........
i need output as
1 smith 423-422-5226, 414-255-5252
2 george 511-522-2525, 524-522-2428
.....
can u any one help me
View 1 Replies
View Related
Jun 12, 2014
I have two issues I'm trying to deal with in my code.
1. I'm trying to group by first and last name, which are in two different columns
2. I'm trying to take an average of pay per miles.
Neither of these is working well. Actually, neither is working at all.
This is the code!
SELECT
OD.DriverID,
(W.FirstName + W.LastName AS 'Driver'),
DATEADD(dd,(DATEDIFF(dd,0,O.ReadyTimeFrom)),0) AS Date,
DATENAME(dw,O.ReadyTimeFrom) AS DayOfTheWeek,
Count(OD.OrderID) AS 'Total Orders',
SUM(O.Distance) AS OrderMiles,
[Code] ....
View 2 Replies
View Related
May 1, 2001
here is the script im using.
SELECT dbo_ITEM.part_no, dbo_SALES_ORDER.entered_date_time, Sum(dbo_SALES_ORDER_ITEM.sales_price) AS SumOfsales_price
FROM dbo_ITEM INNER JOIN (dbo_SALES_ORDER INNER JOIN dbo_SALES_ORDER_ITEM ON dbo_SALES_ORDER.sales_order_id = dbo_SALES_ORDER_ITEM.sales_order_id) ON dbo_ITEM.item_id = dbo_SALES_ORDER_ITEM.item_id
GROUP BY dbo_ITEM.part_no, dbo_SALES_ORDER.entered_date_time
HAVING (((dbo_ITEM.part_no)="5030" Or (dbo_ITEM.part_no)="5040" Or (dbo_ITEM.part_no)="5050" Or (dbo_ITEM.part_no)="5060" Or (dbo_ITEM.part_no)="6014" Or (dbo_ITEM.part_no)="6016" Or (dbo_ITEM.part_no)="6017" Or (dbo_ITEM.part_no)="5071" Or (dbo_ITEM.part_no)="5081" Or (dbo_ITEM.part_no)="5091") AND ((dbo_SALES_ORDER.entered_date_time) Between [Enter Start Date] And [Enter End Date]))
ORDER BY dbo_ITEM.part_no;
If i delete the
((dbo_SALES_ORDER.entered_date_time) Between [Enter Start Date] And [Enter End Date]))
statement than the SUM function works, for some reason (no pun intended) when a date set is entered the SUM statement is inopperative. Any help would be much appriciated.
Thanks
Matthew
View 2 Replies
View Related
Aug 3, 2007
Hi,
I have a table with a userid and duration field. I need to contrast and individual against a group of users from the table. I can get the users cumulative hours by date in the select clause.
I am having a problem producing the group's sum of averages in the main query.I have tried it many ways and just cant get it to work. I need to be able to display something like this below:
Date GV IV
1/1/07 .45 .37
1/2/07 .56 .45
1/3/07 .68 .59
--
So Far I have this:
SELECT
D1.Date,
GV=ROUND(CAST(SUM(D2.Duration) AS FLOAT) / 3600,2),
IV=(SELECT ROUND(CAST(SUM(DurationAll)AS FLOAT) / 3600,2)
FROM IR_UserDaily WHERE UserID=@UserID AND Date<=D1.Date)
FROM
( SELECT Date,Duration=AVG(DurationAll)
FROM IR_UserDaily
WHERE
UserID IN(SELECT FilterID FROM IR_Filter WHERE ReportID=@RID)AND(Date BETWEEN @LowDate and @HighDate)
GROUP BY Date
) AS D1
INNER JOIN
( SELECT Date,Duration=AVG(DurationAll)
FROM IR_UserDaily
WHERE
UserID IN(SELECT FilterID FROM IR_Filter WHERE ReportID=@RID)AND(Date BETWEEN @LowDate and @HighDate)
GROUP BY Date
) AS D2
ON D2.Date < = D1.Date
WHERE (D1.Date BETWEEN @LowDate and @HighDate) AND (D2.Date BETWEEN @LowDate and @HighDate)
GROUP BY D1.Date,D1.Duration
ORDER BY D1.Date
The problem is that the avg function is returning the avg for all values up to the inner join condition, I think.
Can someone help me here I know it should be simple.
View 1 Replies
View Related
Feb 6, 2008
I currently have a pivot table query that is working great but I need to add to it. The below code is giving me the total ServiceTime per date. I need to split this service time out depending on the stage of this note. Basically I need to pivot table queries and join them together.
1) If the note has been signed
2) If the note has been signed and countersigned
SUM(CASE WHEN countersigned_id IS NULL AND signed_id IS NOT NULL THEN ISNULL(d.time_face, 0) + ISNULL(d.time_other, 0) ELSE
0 END) as PendingServiceTime,
SUM(CASE WHEN countersigned_id IS NOT NULL THEN ISNULL(d.time_face, 0) + ISNULL(d.time_other, 0) ELSE
0 END) as ApprovedServiceTime
How do I add this to my pivot table query and the dates are dynamic.
SELECT lastname + ', ' + firstname as FullName, [12/3/2007], [12/4/2007], [12/5/2007]
FROM (SELECT p.LastName, p.FirstName, t.ServiceDate,
ISNULL(d.time_face, 0) + ISNULL(d.time_other, 0) AS ServiceTime
FROM dbo.allNotes(8) AS t
LEFT JOIN dbo.note_Collateral_provider AS d ON d.note_Collateral_id = t.ID
LEFT JOIN dbo.Personnel as p ON d.personnel_id = p.ID
LEFT JOIN dbo.Clients as c on t.ClientID = c.ID
LEFT JOIN fPayor(8) fp on fp.noteId = t.id and fp.dbTable = 'collateral'
LEFT JOIN dbo.payor py ON py.ID = substring(fp.fPayorName, 41, 19)
LEFT JOIN dbo.payorinfo pyInfo ON pyInfo.ID = py.payorinfoid
WHERE t.AgencyID = 8 AND t.tableName = 'collateral'
AND t.not_billable_reason_id IS NULL AND VOID_ID IS NULL
AND ((t.signed_id IS NOT NULL AND t.countersigned_id IS NULL) OR (t.countersigned_id IS NOT NULL))
AND t.ServiceDate BETWEEN CONVERT(DATETIME, '12/03/2007') AND CONVERT(DATETIME, '12/05/2007')
) rs Pivot (SUM(rs.ServiceTime) FOR rs.ServiceDate IN ([12/3/2007], [12/4/2007], [12/5/2007]
View 1 Replies
View Related
Oct 18, 2007
I am trying to write a query that gets daily sales for each of our stores plus WTD and MTD totals
columns would be
Store date daily_total wtd_total mtd_total
the query need to produce a row per store per day and have the wtd sum reset for each week so that it
sums up sales day by day for that week
Is there a good way to do this?
View 3 Replies
View Related
Jun 10, 2006
Hi
Im new in this forum so don't if this is the right place to post these kind of questions..
Im using vb2005 and have made a program that deals with customers and payments.
I have a table called acount. Roughly it contains these columns
Number, amount, type..
type can be a payment or a charge
I would like to have a query that gives me this result:
Number, sum(payments), sum(charges) (grouped by number)
I think it is some type of merging these to querys
select number, sum(amount) where type = 0 group by number
and
select number, sum(amount) where type <> 0 group by number
Im using it to calculate a customers acount to see if they have paid to much or to little.
Any ideas?
View 6 Replies
View Related
Jan 13, 2015
How to get the lowest U.Price along with FX and Rate.
ID-U.Price-FX-Rate
1280 19.1196 EUR 3.85
1280 46.2462 USD 3.63
1280 6.32 RM 1.00
Required output.
ID-U.Price-FX-Rate
1280 6.32 RM 1.00
View 4 Replies
View Related
Dec 9, 2013
I have 4 archive tables and 1 active table that are created the same, but contain different data based on the date. I need to get results that have three columns: AuthorName, Month, Total. This is currently working, but through my research I can't find how to start going about dealing with the fact that each Author has some of his results from one month in one table and some in another table and how to add those together into one row. Example:
(What I'm Getting)
AuthorName Month Total
Test, Fred 3 43
Test, Fred 3 12
Test, Fred 2 56
Test, Fred 5 35
[code]....
View 4 Replies
View Related
Mar 23, 2008
I have an exisitng report that lists unit name, provider, runday, shift, patient. The report groups by unit name and there is a page break after each unit name. So in the current environment the report prints one page per unit that contains all of the providers, rundays, shifts, and patients for that unit name its grouping on. So the report would like like this when it prints:
Unit A
Provider 1 Runday 1 Shift 1
patient 1
patient 2
Provider 1 Runday 1 Shift 2
patient 1
patient 2
Provider 1 Runday 2 Shift 1
patient 1
patient 2
Provider 1 Runday 2 Shift 2
patient 1
patient 2
Provider 2 Runday 1 Shift 1
patient 1
patient 2
Provider 2 Runday 1 Shift 2
patient 1
patient 2
Provider 2 Runday 2 Shift 1
patient 1
patient 2
Provider 2 Runday 2 Shift 2
patient 1
patient 2
PAGE BREAK
Unit B............(repeat data from page 1)
PAGE BREAK
Unit C............(repeat data from page 1
The end user would like the ability to keep the report as is but would like to also be able to print the report as one page per each unit name, provider, runday and shift. so it would look like this
Unit A
Provider 1 Runday 1 Shift 1
patient 1
patient 2
PAGE BREAK
Unit A
Provider 1 Runday 1 Shift 2
patient 1
patient 2
PAGE BREAK
Unit A
Provider 1 Runday 2 Shift 1
patient 1
patient 2
So I created a boolean parameter with a prompt of Page break by Unit, Provider, Runday & Shift? My thought is if the users sets this to False, the report will group on just Unit Name (the first example). If the user sets this to True, the report will group on Unit Name, Provider, Runday & Shift.
I set the grouping expression for this data table as:
=iif(Parameters!Grouping.Value = "False", Fields!unit_Name.Value,(Fields!unit_Name.Value,Fields!Lname.Value,Fields!Rundays.ValueFields!Shift.Value))
Within the expression editor window it displays a syntax error and the report will not run.
Any help would be greatly appreciated!!!!!!!!!
View 7 Replies
View Related
Apr 30, 2015
I have a table Transaction that looks something like the following :
TransactionIDÂ Â Â Â Â Â Â Â Â Â
Currency        Credit             Debit
1Â Â Â Â Â USDÂ Â Â Â Â 500Â Â Â Â Â Â Â Â Â Â Â Â Â 0
2     Afcu          6000            0
[Code] ....
I write query like this
select SUM(credit)-SUM(Debit)as [Balance] ,Source from Transaction group by Source
And it came like
Balance Source         Â
1500Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â USD
6000Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Afcu
6800Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â INR
7000Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Pfc
-200Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â AUD
But I also want to add Afcu , Pfc with USD and want output like
Balance Source
14500Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â USD
6800Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â INR
-200Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â AUD
View 3 Replies
View Related
Dec 24, 2003
i have this query and would like to have a sum for each column. how can i phrase the compute line please ?
select office as Office
, Sum(Case (role) when 'ebp' then 1 else 0 end) as 'EBP'
, Sum(Case (role) when 'support' then 1 else 0 end) as 'Support'
, Sum(Case (role) when 'Awaiting Disposal' then 1 else 0 end) as 'Awaiting Disposal'
, Sum(Case (role) when 'Interview Room' then 1 else 0 end) as 'Interview Room'
, Sum(Case (role) when 'Sch Drop In' then 1 else 0 end) as 'Sch Drop In'
, Sum(Case (role) when 'Sch CX Staff' then 1 else 0 end) as 'Sch CX Staff'
, Sum(Case (role) when 'Not in Use' then 1 else 0 end) as 'Not in Use'
, Sum(Case (role) when 'Public' then 1 else 0 end) as 'Public'
, Sum(Case (role) when 'IAG' then 1 else 0 end) as 'IAG'
, Sum(Case (role) when 'Delivery' then 1 else 0 end) as 'Delivery'
, Sum(Case (role) when 'NVQ Use' then 1 else 0 end) as 'NVQ Use'
, Sum(Case (role) when 'Hot Swap Spare' then 1 else 0 end) as 'Hot Swap Spare'
, Sum(Case (role) when 'Archived' then 1 else 0 end) as 'Archived'
, Sum(Case (role) when 'Network Infrastructure' then 1 else 0 end) as 'Network Infrastructure'
, Sum(Case (role) when 'Unknown' then 1 else 0 end) as 'Unknown'
, Sum(Case (role) when 'Drop in Centres' then 1 else 0 end) as 'Drop in Centres'
, Sum(Case (role) when 'Training' then 1 else 0 end) as 'Training'
from tempassets2
group by office, role
order by office
any help appreciated.
View 2 Replies
View Related
Mar 4, 2008
Hi,
I started working with SRS from the past one month. I am breaking my head to do this. My report has a single stored procedure. I made it to work all values of a parameter like
exec sp_employee 'All' (Returns data for all employees)
exec sp_employee '1111' (Returns data for an employee with id 1111)
exec sp_employee '1111,2222' (Returns data for an employee with id 1111 as well as 2222)
This part works perfectly. I could successfully pass the values as mentioned above using a code block.
Now my challenge is how to layout the data on the report.
I need to show the report as follows:
Employeeid Employee Name Address etc.......
Skills:
Skill# Skill Name
1 11111
2 22222
3 33333
4 44444
Contacts:
Contact Type Contact#
Main 111-1111
Emergency 222-1111
Eductation:
Name University
Degree UofU
Masters UofU
I tried using group by employeeid. But i can only show one group of data either Skills/Contacts/Education.
I do not know if I use sub-report, how to pass the parameter from the main, when I pick multiple values for Employeeid.
Any idea how to do this? I appreciate your help,
Thank you,
View 3 Replies
View Related
Dec 16, 1999
I am trying to build a query in SQL Server 7 that shows my customer ID, customer name, total sales. The query needs to be sorted from highest to Lowest sales. Once the query is sorted I want to put a ranking number beside my total sales field(i.e.1, 2, 3, 4 ....etc.) So far have a query(I did this in Access as a test) that sorts my sales by customer.
Anyone out there know how to get the ranking number beside my sorted list of customers?
Someone has mentioned cursors to me. I have no idea how to use these.
SELECT
Customer.`Customer Name`,
SUM (Customer.`Last Year's Sales`) as total
FROM
`Customer` Customer
GROUP BY
Customer.`Customer Name`
ORDER BY
total DESC
Thanks for the help
Mark
View 2 Replies
View Related
Nov 2, 2003
You are given say a pricelist of books. And you have to find out
all possible sets of books, each of them having total sum of book
prices equal to a given number.
set nocount on
if object_id('tempdb..#t')>0 drop table #t
if object_id('tempdb..#tt')>0 drop table #tt
create table #t (n int, price int)
insert into #t -- note asc order of book prices
select 1, 1 union all
select 2, 3 union all
select 3, 4 union all
select 4, 5 union all
select 5, 7 union all
select 6, 7 union all
select 7, 11 union all
select 8, 15 union all
select 9, 20 union all
select 10, 20 union all
select 11, 22 union all
select 12, 28 union all
select 13, 33 union all
select 14, 40 union all
select 15, 43 union all
select 16, 47 union all
select 17, 50 union all
select 18, 55 union all
select 19, 56 union all
select 20, 63
go
create table #tt (n int, price int)
go
declare @rows int, @p int, @sum int set @sum=16
delete from #t where price>@sum
set @p=(select sum(price) from #t)
if @p>=@sum
begin
set @rows=(select max(n) from #t)
declare @n int, @s int
set @n=@rows+1 set @s=0
while 0=0
begin
while @n>1
begin
set @n=@n-1
if @s+(select price from #t where n=@n)<=@sum
and @s+(select sum(price) from #t where n<=@n)>=@sum
begin
set @s=@s+(select price from #t where n=@n)
insert into #tt select n, price from #t where n=@n
if @s=@sum select * from #tt --- outputting
end
end
set @n=(select min(n) from #tt)
set @s=@s-(select price from #tt where n=@n)
delete from #tt where n=@n
if @s=0 and (select sum(price) from #t where n<@n)<@sum break
end
end
drop table #tt
drop table #t
Result for @sum=16 (for e.g. @sum=76 number of different sets = 196):
n price
----------- -----------
8 15
1 1
n price
----------- -----------
7 11
4 5
n price
----------- -----------
7 11
3 4
1 1
n price
----------- -----------
6 7
4 5
3 4
n price
----------- -----------
6 7
4 5
2 3
1 1
n price
----------- -----------
5 7
4 5
3 4
n price
----------- -----------
5 7
4 5
2 3
1 1
EDIT: added one more condition (in blue) into an IF statement.
Now it works incredibly fast.
View 4 Replies
View Related
Jul 20, 2005
I have just added a third table to a query and I am no longer gettingthe results I am expecting.Three Tables:CUSTINVOICEJOUR (Header Table)CUSTINVOICETRANS (Line Item Table)MARKUPTRANS (Additional Header Info)CUSTINVOICEJOUR has a one to many relationship to CUSTINVOICETRANS.CUSTINVOICEJOUR has a one to many relationship to MARKUPTRANS.I need to sum an integer column from MARKUPTRANS, in rows that arerelated to CUSTINVOICEJOUR, and include that output with my querybelow, which right now has a row for each CUSTINVOICETRANS record:SELECT CUSTINVOICEJOUR.INVOICEAMOUNT, CUSTINVOICETRANS.QTYFROM CUSTINVOICEJOUR INNER JOINCUSTINVOICETRANS ON CUSTINVOICEJOUR.INVOICEID =CUSTINVOICETRANS.INVOICEIDWHERE (CUSTINVOICEJOUR.DATAAREAID = 'acm') AND(CUSTINVOICETRANS.DATAAREAID = 'acm')The above works fine - a row for each record in CUSTINVOICETRANS withthe header info in there as well.I tried the query below to add a SUM() from MARKUPTRANS, but when I runit, I get one row with strange results in it - not what I expected.What am I doing wrong?SELECT CUSTINVOICEJOUR.INVOICEAMOUNT, CUSTINVOICETRANS.QTY,SUM(MARKUPTRANS.VALUE) AS FreightValueFROM CUSTINVOICEJOUR INNER JOINCUSTINVOICETRANS ON CUSTINVOICEJOUR.INVOICEID =CUSTINVOICETRANS.INVOICEID INNER JOINMARKUPTRANS ON CUSTINVOICEJOUR.RECID =MARKUPTRANS.TRANSRECIDWHERE (CUSTINVOICEJOUR.DATAAREAID = 'acm') AND(CUSTINVOICETRANS.DATAAREAID = 'acm') AND (MARKUPTRANS.DATAAREAID ='acm')GROUP BY CUSTINVOICEJOUR.INVOICEAMOUNT, CUSTINVOICETRANS.QTY,MARKUPTRANS.MARKUPCODEHAVING (MARKUPTRANS.MARKUPCODE = 'Freight')
View 1 Replies
View Related
Jul 17, 2013
I have a table of attributes set up as follows:
ID, Value, Group
1, Football, Sports
1, Baseball, Sports
1, Basketball, Sports
2, Baseball, Sports
3, Football, Sports
1, Lambda Sigma, Greeks
2, Delta Delta, Greeks
etc.
I want a query that will combine that values for each ID into one field per group. So if ID 1 has multiple sports but also a greek attribute, they end up with two rows; the first row containing the combined sports values and the second row the greek valued not combined, because there was only one value in that group for that ID. For example:
ID, Combined Values, Group
1, Football Baseball Basketball, Sports
2, Baseball, Sports
3, Football, Sports
1, Lambda Sigma, Greeks
2, Delta Delta, Greeks
View 5 Replies
View Related
Mar 10, 2014
Consider the following dataset:
COL1 | COL2 | COL3 | COL4
1 | FD | DR. A | Y
2 | FD | DR. A | Y
3 | FD | DR. A | N
4 | FD | DR. A | Y
5 | FD | DR. A | Y
6 | PF | DR. A | Y
7 | FD | DR. B | Y
8 | PF | DR. B | N
Consider the script below:
SELECT
COL2, COL3, COUNT(COL1) AS TOTALS
FROM CASES
GROUP BY COL2, COL3
ORDER BY COL3, COL2
The script above produces the following output:
COL2 | COL3 | TOTALS
FD | DR. A | 5
PF | DR. A | 1
FD | DR. B | 1
PF | DR. B | 1
I need to add one more column to the script that counts records with 'Y' in COL4 for each COL1 category (FD, PF). The final dataset would look like this:
COL2 | COL3 | TOTALS | NEWCOL
FD | DR. A | 5 | 4
PF | DR. A | 1 | 1
FD | DR. B | 1 | 1
PF | DR. B | 1 | 0
I am having a hard time trying to use COUNT() on multiple columns with the GROUP BY restrictions that exist.
View 2 Replies
View Related
Jul 19, 2007
If I have a domain user DOMAINuser1 who belongs to multiple window groups say DOMAINLookupConfigUsers and DOMAINAuditConfigUsers. In sqlserver, I would create two logins - DOMAINLookupConfigUsers and DOMAINAuditConfigUsers and matching users in the database. Then I grant LookupConfig role to the LookupConfigUsers user and AuditConfig role to the AuditConfigUsers user in the database. When DOMAINuser1 logs in, will it have both roles? I try to set this up but it does not seem to work. The domain user only picks up one of the role. Am I on the right track? If not, what is the proper way to grant multiple roles to a user when it belongs to multiple groups and each group has different privileges in the database.
View 4 Replies
View Related
Jun 17, 2015
I am using sql server and I have a table called accnt with the fields ven1 and amnt1 and a table called acc1167 with fields ven, job#, and amnt. for this example these tables look like this
    accnt              acc1167
  ven1   amnt1        ven   job#  amnt
  1167   100         1167   1    200   Â
  1152   50          1167   2    300
  1167   110         1167   3    100
  1167   300         1167   4    200
  1252   1050        1167   5    200
  1167   210         1167   6    150
  1167   1150Â
  1167   130Â
  2113   800Â
  1167   550
  1167   1200
I need to sum amnt1 for all the records in accnt with the ven1 of 1167, we will call this sumA. Then sum amnt in acc1167 for all records, we will call this sumB. next I need to divide sumB by sumA to get a ratio. finally I need to multiply each amnt value from acc1167 by the ratio and get a number that will then replace the acc1167 amnt value.
for example, sumA = 3750, sumB = 1150. taking these values, sumB/sumA = 0.307. I then replace every value in acc1167 amnt with 0.307*itself, so the final table should look like this:
     acc1167
  ven  job#   amnt
  1167  1    61.4
  1167  2    92.1
  1167  3    30.7
  1167  4    61.4
  1167  5    61.4
  1167  6    46.05
i have tried to use the sum function and and some insert, but i am very new to SQL and have never used sum before and don't know how to call from multiple tables, or how to store a ratio. Ive tried this:
  UPDATE   acc1167
  sum1 = sum amnt1 where ven1 = '1167'
  from accnt
  sum2 = sum amnt
  from accnt
  SET     amnt = sum2/sum1*amnt
  FROM    acc1167
View 2 Replies
View Related
Aug 3, 2007
Hello All,
I am trying to convert the rows in a table to columns. I have found similar threads on the forum addressing this issue on a high level suggesting the use of cursors, PIVOT Transform, and other means. However, I would appreciate if someone can provide a concrete example in T-Sql for the following subset of my problem.
Consider that we have Product Category, Product and its monthly sales information retrieved as follows:
CategoryID
ProductID
ProductName
Month
UnitPrice
QtySold
SalesAmount
1
1
Panel
Jan
5
10
50
1
1
Panel
Feb
5
15
75
1
1
Panel
Mar
5
20
100
1
2
Frame
Jan
10
30
300
1
2
Frame
Feb
10
25
250
1
2
Frame
Mar
10
20
200
1
3
Glass
Jan
20
10
200
1
3
Glass
Feb
20
20
400
1
3
Glass
Mar
20
30
600
I would like it to be converted into following result set:
CategoryID
ProductID
ProductName
UnitPrice
QtySold_Jan
SalesAmt_Jan
QtySold_Feb
SalesAmt_Feb
QtySold_Mar
SalesAmt_Mar
1
1
Panel
5
10
50
15
75
20
100
1
2
Frame
10
30
300
25
250
20
200
1
3
Glass
20
10
200
20
400
30
600
I have purposefully included QtySold here as I need to display both Quantity and Sales as measured column groups in my report. Can this be achieved in sql? I would appreciate any responses.
Thanks.
View 1 Replies
View Related