Combining result rows - sql

I'm trying to get the result below to be displayed group by Article.
Would this be possible?
So that in the end I will only have 2 lines.
The data from TYPE I & W will be combined.
The image to my query as below
image http://tikistudio.sg/F002.jpg
The query as below
SELECT INTSALEID as RECEIPT,
STRSALETYPE as TYPE,
STRORDERCODE as ARTICLE,
max(case when strsaletype='I' then DBLQTYSOLD else null end) as [QTY SOLD],
max(case when strsaletype='I' then CURSELLPRICE1 else null end) as [UNIT PRICE],
max(case when strsaletype='W' then CUROFFERDISCOUNT else null end) as [DISCOUNT],
max(case when strsaletype='I' then CURFOREIGNAMT else null end) as [GROSS AMOUNT]
FROM DAILYSALES
WHERE STRTRADECODE='MM01'
and DTMTRADEDATE='01-01-2015' and INTSALEID='31086'
and STRSALETYPE in ('I','W')
GROUP BY STRORDERCODE,STRSALETYPE,INTSALEID,DBLQTYSOLD,CURSELLPRICE1,
CURFOREIGNAMT,CURDISCOUNT,CUROFFERDISCOUNT

You have to remove some columns in Group By
SELECT
INTSALEID as RECEIPT,
STRORDERCODE as ARTICLE,
MAX(CASE WHEN strsaletype='I' THEN DBLQTYSOLD ELSE NULL END) as [QTY SOLD],
MAX(CASE WHEN strsaletype='I' THEN CURSELLPRICE1 ELSE NULL END) as [UNIT PRICE],
MAX(CASE WHEN strsaletype='W' THEN CUROFFERDISCOUNT ELSE NULL END) as [DISCOUNT],
MAX(CASE WHEN strsaletype='I' THEN CURFOREIGNAMT ELSE NULL END) as [GROSS AMOUNT]
FROM DAILYSALES
WHERE
STRTRADECODE='MM01'
and DTMTRADEDATE='01-01-2015' and INTSALEID='31086'
and STRSALETYPE in ('I','W')
GROUP BY STRORDERCODE,INTSALEID

If you aggregate your data one more time grouping by Receipt, and Article, taking the max value for QTY Sold, Unit Price, Gross Amount and Min Value for Discount.
Select RECEIPT, ARTICLE, MAX([QTY SOLD]) as [QTY SOLD], MAX([UNIT PRICE]) as [UNIT PRICE], MIN([DISCOUNT]) as [DISCOUNT], MAX([GROSS AMOUNT]) as [GROSS AMOUNT]
From
(select INTSALEID as RECEIPT,
STRSALETYPE as TYPE,
STRORDERCODE as ARTICLE,
max(case when strsaletype='I' then DBLQTYSOLD else null end) as [QTY SOLD],
max(case when strsaletype='I' then CURSELLPRICE1 else null end) as [UNIT PRICE],
max(case when strsaletype='W' then CUROFFERDISCOUNT else null end) as [DISCOUNT],
max(case when strsaletype='I' then CURFOREIGNAMT else null end) as [GROSS AMOUNT]
from DAILYSALES
where STRTRADECODE='MM01'
and DTMTRADEDATE='01-01-2015' and INTSALEID='31086'
and STRSALETYPE in ('I','W')
group by STRORDERCODE,STRSALETYPE,INTSALEID,DBLQTYSOLD,CURSELLPRICE1,
CURFOREIGNAMT,CURDISCOUNT,CUROFFERDISCOUNT) x
Group by RECEIPT, ARTICLE

Related

sql query group/sum and turn rows into combined columns

I am trying to turn the source table into a summation table on a few factors.
Can someone point me in the right direction?
date and id will be the rows.
exprev and type will be combined to create a column
amount will be summed
I tried pivot table but I couldn't figure out a way to combine columns, ie. 'rent expense'
UPDATE
conditional aggregation works but I forgot to add one more scenario.
I need to add a column for the currency of the item, then change the result to have a local amount, and a converted amount to USD.
new screenshot below
update...
I added to the select and the group by.
,case when a.exprev = 'Expense' and a.type= 'rent' then a.Currency else 'nothing' end as [rent Currency]
now I am getting an extra row of inaccurate data in my result.
it has created 2 lines of data for each id when it should be only 1 line of data
for argument sake... lets say I will know the exact columns
In that case you would use conditional aggregation, like this:
SELECT [date], id
,SUM(case when exprev = 'expense' and type='rent' then amount else 0 end) [rent expense]
,SUM(case when exprev = 'revenue' and type='rent' then amount else 0 end) [rent revenue]
,SUM(case when exprev = 'expense' and type='tax' then amount else 0 end) [tax expense]
,SUM(case when exprev = 'revenue' and type='tax' then amount else 0 end) [tax revenue]
,SUM(case when exprev = 'expense' and type='insurance' then amount else 0 end) [insurance expense]
,SUM(case when exprev = 'revenue' and type='insurance' then amount else 0 end) [insurance revenue]
FROM [table]
GROUP BY [date], id

How can I get the difference of 2 variables in Microsoft SQL?

I am trying to find the difference between the revenue of customers who have not churned vs customers who have. This is what I have:
Select sum ([monthly charge]) as Non_Churned_Revenue
from portfolioproject..telecom_churn
Where [Customer Status] = 'Joined' OR [Customer Status] = 'Stayed'
Select sum ([monthly charge]) as Churned_Revenue
from portfolioproject..telecom_churn
Where [Customer Status] = 'Churned'
How would I be able to subtract Churned_Revenue from Non_Churned_Revenue? I keep getting errors when I try.
Thanks!
You are looking for conditional aggregation
SELECT
SUM(CASE WHEN tc.[Customer Status] IN ('Joined', 'Stayed') THEN tc.[monthly charge] END) AS Non_Churned_Revenue
SUM(CASE WHEN tc.[Customer Status] = 'Churned' THEN tc.[monthly charge] END) AS Churned_Revenue,
SUM(CASE WHEN tc.[Customer Status] IN ('Joined', 'Stayed') THEN tc.[monthly charge] END)
-
SUM(CASE WHEN tc.[Customer Status] = 'Churned' THEN tc.[monthly charge] END) AS Difference
FROM telecom_churn tc;

SQL Query with RollUp

this is my query
select X.Memo, X.Month, Format(sum(X.[Total Sales S$]),'#,0.00') as [Rental Sales $]
, Format(sum(X.[Net GP S$]),'#,0.00') as [Rental GP $]
from Data X
group by X.Month,X.Memo
This is my result:
Expected result should be like this:
is it possible to do it in SQL? Can help me in the query?
One way would be to use case statement and get the result you mentioned.
you can add requird columns in the similar way and get the output.
SELECT MONTH,
sum(CASE WHEN Memo = 'Rental' THEN sales$ END) Rental_$,
sum(CASE WHEN Memo = 'Rental' THEN GP$ END) Rental_GP,
sum(CASE WHEN Memo = 'Sales' THEN sales$ END) Sales_$,
sum(CASE WHEN Memo = 'Sales' THEN GP$ END) Sales_GP
FROM tablea
GROUP BY MONTH
SELECT MONTH,
Format(sum(CASE WHEN Memo = 'Rental' THEN (X.[Total Sales S$]) END), '#,0.00') Rental_$,
Format(sum(CASE WHEN Memo = 'Rental' THEN (X.[Net GP S$]) END), '#,0.00') Rental_GP,
Format(sum(CASE WHEN Memo = 'Sales' THEN (X.[Total Sales S$]) END), '#,0.00') Sales_$,
Format(sum(CASE WHEN Memo = 'Sales' THEN (X.[Net GP S$]) END), '#,0.00') Sales_GP,
Format((sum(CASE WHEN Memo = 'Rental' THEN (X.[Total Sales S$]) END) + sum(CASE WHEN Memo = 'Sales' THEN (X.[Total Sales S$]) END)), '#,0.00') [Total Sales S$],
Format((sum(CASE WHEN Memo = 'Rental' THEN (X.[Net GP S$]) END) + sum(CASE WHEN Memo = 'Sales' THEN (X.[Net GP S$]) END)), '#,0.00') [Total GP S$]
FROM DATA X
GROUP BY MONTH WITH ROLLUP
ORDER BY SUM(X.MN) ASC

Issue pivoting out Data (Currency Causing the issue)

I am creating a view that will pivot out Value Types for a set of data. The issue is that I have 5 unique values for currency (EUR, USD, MYR, CYN, NULL), and yes I realize NULL is not a value, but NULL is the issue. While I do want a different line of data for different currencies, I do not want a different line for NULL, as NULL simply means that Currency isn't used in that specific value type (SalesVolume). The same thing happens with UOM. I simply want a single line of data (for each currency (There is only a single UOM)). Here is my query:
SELECT Year, Period, [Year-Period], Region, [Op Co] AS OpCo, PMC, [PMC Description] AS PMCDescription, Currency, UOM,
MAX(CASE WHEN [Value Type] = 'Net Revenue' THEN Value END) AS NetRevenue,
MAX(CASE WHEN [Value Type] = 'Sales Volume' THEN Value END) AS SalesVolume,
MAX(CASE WHEN [Value Type] = 'Std Gross Margin' THEN Value END) AS StdGrossMargin,
[Customer Relationship] AS CustomerRelationship
FROM gdw.FactBudgetSummaryNew
GROUP BY Year, Period, [Year-Period], Region, [Op Co], PMC, [PMC Description], Currency, UOM, [Customer Relationship]
I currently get this:
But, as you can see, for Sales Volume, the value for Currency is NULL, which causes an additional column, I'd like it to just combine.
Seems up have different data mixed up together. Try calculating grouping by UOM (if it's just 1 different value) separately from the Currency grouping.
;WITH UOMData AS
(
SELECT
Year,
Period,
[Year-Period],
Region,
[Op Co] AS OpCo,
PMC,
[PMC Description] AS PMCDescription,
UOM,
MAX(CASE WHEN [Value Type] = 'Sales Volume' THEN Value END) AS SalesVolume,
[Customer Relationship] AS CustomerRelationship
FROM
gdw.FactBudgetSummaryNew
WHERE
UOM IS NOT NULL
GROUP BY
Year,
Period,
[Year-Period],
Region,
[Op Co],
PMC,
[PMC Description],
UOM,
[Customer Relationship]
),
CurrencyData AS
(
SELECT
Year,
Period,
[Year-Period],
Region,
[Op Co] AS OpCo,
PMC,
[PMC Description] AS PMCDescription,
Currency,
MAX(CASE WHEN [Value Type] = 'Net Revenue' THEN Value END) AS NetRevenue,
MAX(CASE WHEN [Value Type] = 'Std Gross Margin' THEN Value END) AS StdGrossMargin,
[Customer Relationship] AS CustomerRelationship
FROM
gdw.FactBudgetSummaryNew
WHERE
Currency IS NOT NULL
GROUP BY
Year,
Period,
[Year-Period],
Region,
[Op Co],
PMC,
[PMC Description],
Currency,
[Customer Relationship]
)
SELECT
M.Year,
M.Period,
M.[Year-Period],
M.Region,
M.OpCo,
M.PMC,
M.PMCDescription,
M.UOM,
C.Currency,
M.CustomerRelationship,
M.SalesVolume,
C.StdGrossMargin,
C.NetRevenue
FROM
UOMData AS M
INNER JOIN CurrencyData AS C ON
M.Year = C.Year AND
M.Period = C.Period AND
M.[Year-Period] = C.[Year-Period] AND
M.Region = C.Region AND
M.OpCo = C.OpCo AND
M.PMC = C.PMC AND
M.PMCDescription = M.PMCDescription AND
M.CustomerRelationship = C.CustomerRelationship
Would this work?
MAX(CASE
WHEN [Value Type] = 'Net Revenue' AND UOM IS NOT NULL THEN Value
END) AS NetRevenue,
MAX(CASE
WHEN [Value Type] = 'Sales Volume' AND Currency IS NOT NULL THEN Value
END) AS SalesVolume,
MAX(CASE
WHEN [Value Type] = 'Std Gross Margin' AND UOM IS NOT NULL THEN Value
END) AS StdGrossMargin,
[Customer Relationship] AS CustomerRelationship
FROM gdw.FactBudgetSummaryNew
GROUP BY YEAR,
Period,
[Year-Period],
Region,
[Op Co],
PMC,
[PMC Description],
Currency,
UOM,
[Customer Relationship]

UNION not ouputting correct combined data in SQL/SSRS server 2008

I am a NEWBIE, self taught SQL creator.
I have created a report that uses a series of queries to create 2 temp tables that need joined together.
When I run the report in SQL, I actually get the first temp table as a result, then I get the combined (UNION) result that I want as well.
Then, when I imported this SQL into SSRS and created the pretty report, I'm only getting the results of the FIRST temp table. How do I correct this? Here is the union statement that is supposed to combine the results of the two temp tables.
--declare #StartDate datetime
--declare #EndDate datetime
--declare #FirstGL nvarchar(9)
--declare #LastGL nvarchar(9)
--set #StartDate = '07-01-2014'
--set #EndDate = '02-01-2015'
--------------Temp Table #1 - Pulls invoice detail from AP for a selected time period and selected GL account numbers -------------------
select gl.acc_ext_id as [GL #]
,rtrim(gl.acc_ds) as [Account Descr]
,convert(varchar(10),ih.ivo_dt,101) as [Activity Date]
,((rtrim(vm.org_nm) + ' Inv#: ' + rtrim(ih.ivo_ext_id) + ' ' + (CASE WHEN ih.ivo_ds IS NULL THEN ' ' ELSE rtrim(ih.ivo_ds) END) + (CASE WHEN id.ivo_dtl_ds IS NULL THEN ' ' ELSE rtrim(id.ivo_dtl_ds) END))) as [Journal Descr]
,CAST(id.ivo_prc_at as decimal(12,2)) as [Inv Amt]
into #APDetail
from TAP600_INVOICE_HDR ih inner join TAP650_INVOICE_DTL id on id.ivo_int_id = ih.ivo_int_id
inner join TAP300_VENDOR_MASTER vm on vm.vnd_int_id = ih.vnd_int_id
inner join TGL910_CHART_OF_ACCOUNTS gl on gl.acc_int_id = id.acc_int_id
where gl.acc_ext_id between #FirstGL and #LastGL
and ih.ivo_dt > #StartDate and ih.ivo_dt < #EndDate
order by gl.acc_ext_id, ih.ivo_dt
------------------Temp Table #2 - Takes temp table #APDetail and moves Inv Amt to either DR or CR field and limits length of description to 75 characters
select distinct [GL #]
, [Account Descr]
, [Activity Date]
, [Journal Descr]
, [Inv Amt]
into #APDetailUpdate
from #APDetail
alter table #APDetailUpdate
add Debit decimal(12,2)
update apu
set apu.Debit = ap.[Inv Amt]
from #APDetailUpdate apu left join #APDetail ap on ap.[GL #] = apu.[GL #] and ap.[Account Descr] = apu.[Account Descr] and ap.[Activity Date] = apu.[Activity Date] and ap.[Journal Descr] = apu.[Journal Descr]
where ap.[Inv Amt] > 0 or ap.[Inv Amt] = 0
alter table #APDetailUpdate
add Credit decimal(12,2)
update apu
set apu.Credit = ap.[Inv Amt]
from #APDetailUpdate apu left join #APDetail ap on ap.[GL #] = apu.[GL #] and ap.[Account Descr] = apu.[Account Descr] and ap.[Activity Date] = apu.[Activity Date] and ap.[Journal Descr] = apu.[Journal Descr]
where ap.[Inv Amt]<0
select [GL #]
, [Account Descr]
, [Activity Date]
, [Journal Descr]
--, [Inv Amt]
, [Debit]
, [Credit]
from #APDetailUpdate
order by [GL #], [Activity Date]
--------------Temp Table #3 - Pulls journal entry detail from GL for a selected time period and selected GL account numbers---------------------
select gl.acc_ext_id as [GL #]
,rtrim(gl.acc_ds) as [Account Descr]
,convert(varchar(10),jh.jnl_pst_dt,101) as [Activity Date]
,(CASE WHEN jd.jnl_dtl_ds IS NULL THEN jh.sys_cd + ' - ' + jh.src_ds ELSE jd.jnl_dtl_ds END) as [Journal Descr]
,sum((CASE WHEN jd.jnl_pst_deb_at IS NULL THEN '0.00' ELSE jd.jnl_pst_deb_at END)) as [Debit]
,sum((CASE WHEN jd.jnl_pst_crd_at IS NULL THEN '0.00' ELSE jd.jnl_pst_crd_at END)) as [Credit]
into #GLDetail
from TGL220_JE_HDR jh inner join TGL250_JE_DTL jd on jd.jnl_int_id = jh.jnl_int_id
inner join TGL910_CHART_OF_ACCOUNTS gl on gl.acc_int_id = jd.acc_int_id
where gl.acc_ext_id between #FirstGL and #LastGL
and jh.jnl_pst_dt > #StartDate
and sys_cd <> 'AP'
group by gl.acc_ext_id, gl.acc_ds, jh.jnl_pst_dt,(CASE WHEN jd.jnl_dtl_ds IS NULL THEN jh.sys_cd + ' - ' + jh.src_ds ELSE jd.jnl_dtl_ds END)
order by gl.acc_ext_id, jh.jnl_pst_dt
-----------------------Final Report - Combines the two tables with a Union statement --------------------
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN apu.[Debit] IS NULL then 0.00 else apu.[Debit] END) as Debit,
(CASE WHEN apu.[Credit] IS NULL then 0.00 else apu.[Credit] END)as Credit
from #APDetailUpdate apu
UNION
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN [Debit] IS NULL then 0 else [Debit] END), (CASE WHEN [Credit] IS NULL then 0 else [Credit] END)
from #GLDetail
order by [GL #], [Activity Date]
Your problem is you're running two select statements:
select [GL #]
, [Account Descr]
, [Activity Date]
, [Journal Descr]
--, [Inv Amt]
, [Debit]
, [Credit]
from #APDetailUpdate
order by [GL #], [Activity Date]
and
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN apu.[Debit] IS NULL then 0.00 else apu.[Debit] END) as Debit,
(CASE WHEN apu.[Credit] IS NULL then 0.00 else apu.[Credit] END)as Credit
from #APDetailUpdate apu
UNION
select [GL #],
[Account Descr],
[Activity Date],
substring([Journal Descr],1,75),
(CASE WHEN [Debit] IS NULL then 0 else [Debit] END), (CASE WHEN [Credit] IS NULL then 0 else [Credit] END)
from #GLDetail
order by [GL #], [Activity Date]
SSRS will only ever return the results of the first select to be used as a dataset. You need to choose which one you want to be displayed as the dataset and then run a separate query in another dataset for the other select. Either that or union them all or remove the first select statement.
Hope this helps.