Issue pivoting out Data (Currency Causing the issue) - sql

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]

Related

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;

why my query is not working. i wrote a query for identifying number of absent and number of present

select [First Name],[Last Name],Class,
(
select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='P'
) as [No Of Present],
(
select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='A'
)as [No Of Absent]
from Attendence
where [Date] between '2018-09-1' and '2018-09-30'
This is a I wrote for my software but it is not giving the right outcome. I want to calculate amount of present and absent for students.
use conditional aggregation:
select [First Name],[Last Name],Class from
count(case [Student Status] ='P' then 1 end) as [No Of Present],
count(case [Student Status] ='A' then 1 end)as [No Of Absent]
from Attendence where [Date] between '2018-09-1' and '2018-09-30' and [Roll Number] ='1'
group by [First Name],[Last Name],Class
Your subquery is different from outer query, it should be correlated :
But, you can do in single select statement with case expression instead of two subquery :
select [First Name], [Last Name], Class,
sum(case when [Student Status] = 'P' then 1 else 0 end) as [No Of Present],
sum(case when [Student Status] = 'A' then 1 else 0 end) as [No Of Absent]
from Attendence at
where [Date] between '2018-09-1' and '2018-09-30' and [Roll Number] = '1'
group by [First Name], [Last Name], Class;
I think your query might work, but you forgot to use distinct. Please find the below rectified query :
select distinct [First Name],[Last Name],Class,
(
select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='P'
) as [No Of Present],
(
select count([Date]) from Attendence where [Roll Number] ='1' and [Student Status] ='A'
)as [No Of Absent]
from Attendence
where [Date] between '2018-09-1' and '2018-09-30'
group by [First Name],[Last Name],Class

Combining result rows

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

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.

Most used tendertype per store T-SQL

I need some help building this MSSQL Query.
I have a table with payment info.
In the table "payment_entry" is a field for Storenumber and Tendertype.
Every new purchase creates a new line in the table "payment_entry" with "store" and "tendertype".
There are two tendertypes "1" or "3".
1 means credit/debit card and 3 means cash.
I want a query that groups by store how many percent of the customers in each store pays cash and how many pays by card.
Thanks in advance!!
EDIT:
Well im no good at SQL but this gave me a count per store for tendertype 1.. Now im stuck..
Select [company$Trans_ Payment Entry].[Store No_],
Count([company$Trans_ Payment Entry].[Tender Type])
From [company$Trans_ Payment Entry] [company$Trans_ Payment Entry]
Where [company$Trans_ Payment Entry].[Tender Type] = '1'
Group By [company$Trans_ Payment Entry].[Store No_]
Order By [company$Trans_ Payment Entry].[Store No_]
;WITH Store_Totals AS
(
SELECT [Store No_] AS StoreNum
,SUM(CASE WHEN tendertypes = 1 THEN 1 ELSE 0 END) AS Credit_Trans
,SUM(CASE WHEN tendertypes = 3 THEN 1 ELSE 0 END) AS Cash_Trans
,COUNT(tendertypes) AS Total_Trans
FROM [company$Trans_ Payment Entry]
GROUP BY [Store No_]
)
SELECT StoreNum
,Credit_Trans / Total_Trans AS Average_Credit
,Cash_Trans / Total_Trans AS Average_Cash
FROM Store_Totals
you can do this with CASE based aggregation
SELECT store,
(SUM(CASE WHEN tendertype =1 THEN 1 ELSE 0 END)*100.0/COUNT(tenderType)) AS CreditPerc,
SUM(CASE WHEN tendertype =3 THEN 1 ELSE 0 END)*100.0/COUNT(tenderType) as CashPerc
FROM payment_entry
GROUP BY store