Numerous Unions, Easier Way? - sql

I'm using the query below and am getting the results I want, I just can't help but think that there is probably a better way than to repeat that code over and over with a different where clause? Recommendations?
WITH HHSUMMARY
AS
(
SELECT
B.HouseholdId, SUM(B.Balance) AS AUM, SUM(B.TradeRevenue + B.TrailRevenue + B.AdvisoryRevenue) AS Revenue
FROM
BookSegmentation.BookSegmentationDataset B
WHERE
B.RepName = 'Rep'
GROUP BY
B.HouseholdId
)
SELECT
'< 25K' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM < 25000
UNION
SELECT
'25K-50K' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 25000 AND AUM < 50000
UNION
SELECT
'50K-100K' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 50000 AND AUM < 100000
UNION
SELECT
'100K-250K' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 100000 AND AUM < 250000
UNION
SELECT
'250K-500K' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 250000 AND AUM < 500000
UNION
SELECT
'500K-750K' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 500000 AND AUM < 750000
UNION
SELECT
'750K-1MM' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 750000 AND AUM < 1000000
UNION
SELECT
'1MM-5MM' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 1000000 AND AUM < 5000000
UNION
SELECT
'> 5MM' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
WHERE AUM >= 5000000
UNION
SELECT
'TOTAL' AS [ACCT BALANCE CAT],
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
here are my results:

Yes, there is a better way. You can define the group in the CTE, and then use the group with GROUP BY:
WITH HHSUMMARY AS (
SELECT B.HouseholdId, SUM(B.Balance) AS AUM,
SUM(B.TradeRevenue + B.TrailRevenue + B.AdvisoryRevenue) AS Revenue,
(CASE WHEN SUM(B.BALANCE) < 25000 THEN '<25000'
WHEN SUM(B.BALANCE) < 50000 THEN '25K-50K'
. . .
END) as [ACCT BALANCE CAT]
FROM BookSegmentation.BookSegmentationDataset B
WHERE B.RepName = 'Rep'
GROUP BY B.HouseholdId
)
SELECT COALESCE([ACCT BALANCE CAT], 'Total'),
COUNT(HouseholdID) AS HH,
CAST(COUNT(HouseholdId) AS DECIMAL(18,2))/(SELECT CAST(COUNT(HouseholdId) AS DECIMAL(18,2)) FROM HHSUMMARY) AS [% HH],
SUM(AUM) AS [HH AUM],
SUM(AUM)/(SELECT SUM(AUM) FROM HHSUMMARY) AS [HH AUM %],
SUM(Revenue) AS REVENUE,
SUM(Revenue)/(SELECT SUM(Revenue) FROM HHSUMMARY) AS [% REV],
SUM(Revenue)/SUM(AUM) AS [EFFICIENCY %]
FROM HHSUMMARY
GROUP BY GROUPING SETS ( ([ACCT BALANCE CAT]), () );
Notice the use of GROUPING SETS to calculate the total. You can also use ROLLUP.

Related

Incorrect 4th & 1st Quarter Sales Values in query

I've been writing a query to group sales by year with other columns containing quarterly sales, growth per quarter in percentage, quarter on quarter change in quarterly sales and total annual sales in the last column from the .
I have ran the following query:
WITH Sales_By_Quarter AS
(
SELECT
DATEPART(YEAR, OrderDate) AS [Year],
DATEPART(QUARTER, OrderDate) AS [Quarter],
SUM(TotalDue) AS [Quarterly Sales],
SUM(TotalDue) - LAG(SUM(TotalDue)) OVER (PARTITION BY DATEPART(YEAR, OrderDate) ORDER BY DATEPART(QUARTER, OrderDate)) AS [Change]
FROM Sales.SalesOrderHeader
GROUP BY DATEPART(YEAR, OrderDate), DATEPART(QUARTER, OrderDate)
),
Annual_Sales AS
(
SELECT
[Year],
SUM([Quarterly Sales]) AS [Total Annual Sales],
SUM([Quarterly Sales]) - LAG(SUM([Quarterly Sales])) OVER (ORDER BY [Year]) AS [Annual Growth]
FROM Sales_By_Quarter
GROUP BY [Year]
)
-- SELECT * FROM Annual_Sales;
SELECT
Sales_By_Quarter.[Year],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 1 THEN Sales_By_Quarter.[Quarterly Sales] END) AS [Q1],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 1 THEN (Sales_By_Quarter.[Quarterly Sales]/Annual_Sales.[Total Annual Sales]*100) END) as [Annual %],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 1 THEN Sales_By_Quarter.[Quarterly Sales] END) AS [4 to 1],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 2 THEN Sales_By_Quarter.[Quarterly Sales] END) AS [Q2],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 2 THEN Sales_By_Quarter.[Quarterly Sales]/Annual_Sales.[Total Annual Sales]*100 END) as [Annual %],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 2 THEN Sales_By_Quarter.[Change] END) AS [1 to 2],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 3 THEN Sales_By_Quarter.[Quarterly Sales] END) AS [Q3],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 3 THEN Sales_By_Quarter.[Quarterly Sales]/Annual_Sales.[Total Annual Sales]*100 END) as [Annual %],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 3 THEN Sales_By_Quarter.[Change] END) AS [2 to 3],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 4 THEN Sales_By_Quarter.[Quarterly Sales] END) AS [Q4],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 4 THEN Sales_By_Quarter.[Quarterly Sales]/Annual_Sales.[Total Annual Sales]*100 END) as [Annual %],
SUM(CASE WHEN Sales_By_Quarter.[Quarter] = 4 THEN Sales_By_Quarter.[Change] END) AS [3 to 4],
Annual_Sales.[Total Annual Sales]
FROM Sales_By_Quarter
JOIN Annual_Sales ON Sales_By_Quarter.[Year] = Annual_Sales.[Year]
GROUP BY Sales_By_Quarter.[Year], Annual_Sales.[Total Annual Sales], Annual_Sales.[Annual Growth]
ORDER BY Sales_By_Quarter.[Year];
I am getting right values in all columns except the 4 to 1 column. I need some help in fixing this query.
Fixed the definition of Quarterly Change, by not Partitioning on Year, and just Ordering by it instead.
Removed the uneccesary CTE (and the join on it) for yearly figures.
Corrected the column being pivoted for [4 to 1].
Ensured all columns have unique names.
WITH
Sales_By_Quarter AS
(
SELECT
DATEPART(YEAR, OrderDate) AS [Year],
DATEPART(QUARTER, OrderDate) AS [Quarter],
SUM(TotalDue) AS [Quarterly Sales],
SUM(TotalDue) - LAG(SUM(TotalDue)) OVER (ORDER BY DATEPART(YEAR, OrderDate), DATEPART(QUARTER, OrderDate)) AS [Change]
FROM
Sales.SalesOrderHeader
GROUP BY
DATEPART(YEAR, OrderDate),
DATEPART(QUARTER, OrderDate)
)
SELECT
Q.[Year],
SUM(CASE WHEN Q.[Quarter] = 1 THEN Q.[Quarterly Sales] END) AS [Q1],
SUM(CASE WHEN Q.[Quarter] = 1 THEN Q.[Quarterly Sales] END) * 100.0 / SUM(Q.[Quarterly Sales]) AS [Q1 Annual %],
SUM(CASE WHEN Q.[Quarter] = 1 THEN Q.[Change] END) AS [4 to 1],
SUM(CASE WHEN Q.[Quarter] = 2 THEN Q.[Quarterly Sales] END) AS [Q1],
SUM(CASE WHEN Q.[Quarter] = 2 THEN Q.[Quarterly Sales] END) * 100.0 / SUM(Q.[Quarterly Sales]) AS [Q2 Annual %],
SUM(CASE WHEN Q.[Quarter] = 2 THEN Q.[Change] END) AS [1 to 2],
SUM(CASE WHEN Q.[Quarter] = 3 THEN Q.[Quarterly Sales] END) AS [Q3],
SUM(CASE WHEN Q.[Quarter] = 3 THEN Q.[Quarterly Sales] END) * 100.0 / SUM(Q.[Quarterly Sales]) AS [Q3 Annual %],
SUM(CASE WHEN Q.[Quarter] = 3 THEN Q.[Change] END) AS [2 to 3],
SUM(CASE WHEN Q.[Quarter] = 4 THEN Q.[Quarterly Sales] END) AS [Q4],
SUM(CASE WHEN Q.[Quarter] = 4 THEN Q.[Quarterly Sales] END) * 100.0 / SUM(Q.[Quarterly Sales]) AS [Q4 Annual %],
SUM(CASE WHEN Q.[Quarter] = 4 THEN Q.[Change] END) AS [3 to 4],
SUM(Q.[Quarterly Sales]) AS [Total Annual Sales],
SUM(Q.[Quarterly Sales]) - LAG(SUM(Q.[Quarterly Sales])) OVER (ORDER BY Q.[Year]) AS [Annual Growth]
FROM
Sales_By_Quarter As Q
GROUP BY
Q.[Year]
ORDER BY
Q.[Year]

Running total with if clause or do while

Consider the following table with 3 columns.
Use this to create a SQL query to list the top products by revenue that make up 25% of the total revenue in 2020.
(i.e. If total revenue is 1000 then list of top products that account for <= 250)
Table ProductRevenue:
Date_DD ... date(YYYY-MM-DD)
Product_Name ... varchar(250)
Revenue ... decimal(10,2)
Sample data:
Date_DD Product_Name Revenue
-------------------------------------
2020-11-30 a 100
2020-10-02 b 100
2020-07-07 c 100
2020-04-04 d 100
2020-05-05 f 50
2020-06-06 g 120
2020-05-30 h 90
2020-11-13 k 120
2020-01-30 l 120
I used that code but don't know how to use where clause . Anyone can help?
SELECT
product_name, revenue,
SUM(revenue) OVER (ORDER BY revenue DESC, product_name) AS running _total
FROM
TABLE_PRODUCT_REVENUE
new code
select product_name, revenue, running_total from
(SELECT product_name, revenue, SUM(revenue) OVER ( ORDER BY revenue DESC, product_name) AS running_total
FROM TABLE_PRODUCT_REVENUE ) o
where running_total<(select max(running_total) from
(SELECT product_name, revenue, SUM(revenue) OVER ( ORDER BY revenue DESC, product_name) AS running_total
FROM TABLE_PRODUCT_REVENUE ) o )*0.25
group by product_name, revenue, running_total
order by running_total
I just need to know where can i add where clause where YEAR([Date_DD])=2000 anyone can help?
The question was not very descriptive; however, below might help you narrow down the issue.
Below will show up you the running total for the Product.
SELECT
product_name, revenue,
SUM(revenue) OVER (partition by product_name ORDER BY revenue DESC, product_name) AS running _total
FROM
TABLE-PRODUCT_REVENUE
below would give the result if the product total is more significant than x amount
select
*,case when running _total >=1000 then 'top selling product' else null end
(
SELECT
product_name, revenue,
SUM(revenue) OVER (partition by product_name ORDER BY revenue DESC, product_name) AS running _total
FROM
TABLE-PRODUCT_REVENUE
)t
where running_total >= xxx amount

Display Percentage of grouped SUM to total SUM

I currently have results like
total sales | total cost | total profit | department
----------------------------------------------------
100 50 50 A
80 20 60 B
250 120 130 C
Using columns from tables
Invoice_Itemized
itemnum | costper | priceper | quantity | invoice_number
--------------------------------------------------------
Invoice_Totals
invoice_number | datetime
---------------------------
Inventory
itemnum | dept_id
------------------
Departments
dept_id | description
----------------------
with the following code
select sum(invoice_itemized.priceper* invoice_itemized.quantity) as "Total Sales",
sum(invoice_itemized.quantity*inventory.cost) as "Total Cost",
sum(invoice_itemized.priceper* invoice_itemized.quantity)-
sum(invoice_itemized.quantity*inventory.cost) as "Total Profit",
departments.description as Department
from invoice_itemized, invoice_totals, inventory, departments
where invoice_itemized.invoice_number=invoice_totals.invoice_number
and year(invoice_totals.datetime)=2018 and month(invoice_totals.datetime)=10
and inventory.itemnum=invoice_itemized.itemnum
and inventory.dept_id=departments.dept_id
and departments.description<>'shop use'
and departments.description<>'none'
and departments.description<>'ingredients'
group by departments.description
order by "total profit" desc
I would like results like
total sales | total cost | total profit | percentage total profit | department
-------------------------------------------------------------------------------
100 50 50 20.83 A
80 20 60 25 B
250 120 130 54.17 C
The problem I encounter is that I'm trying to divide a the grouped results of a SUM-SUM by the total of the same SUM-SUM. I've tried something similar to the suggestion made in
Percentage from Total SUM after GROUP BY SQL Server
but that didn't seem to work for me. I was getting binding errors. Any suggestions?
You can do this with window functions:
with t as (
<your query here>
)
select t.*,
profit * 100.0 / sum(profit) over () as profit_percentage
from t;
This should work:
Select q.[Total Sales],
q.[Total Cost],
q.[Total Profit],
q.Total Profit] / q1.Total Profit] as [Percentage Total Profit],
q.Department
from (
select sum(invoice_itemized.priceper* invoice_itemized.quantity) as [Total Sales],
sum(invoice_itemized.quantity*inventory.cost) as [Total Cost],
sum(invoice_itemized.priceper* invoice_itemized.quantity) - sum(invoice_itemized.quantity*inventory.cost) as [Total Profit],
departments.description as Department
from invoice_itemized, invoice_totals, inventory, departments
where invoice_itemized.invoice_number=invoice_totals.invoice_number
and year(invoice_totals.datetime)=2018 and month(invoice_totals.datetime)=10
and inventory.itemnum=invoice_itemized.itemnum
and inventory.dept_id=departments.dept_id
and departments.description<>'shop use'
and departments.description<>'none'
and departments.description<>'ingredients'
group by departments.description) q
join (
select sum(t.[Total Profit]) as [Total Profit]
from (select sum(invoice_itemized.priceper* invoice_itemized.quantity) as [Total Sales],
sum(invoice_itemized.quantity*inventory.cost) as [Total Cost],
sum(invoice_itemized.priceper* invoice_itemized.quantity) - sum(invoice_itemized.quantity*inventory.cost) as [Total Profit],
departments.description as Department
from invoice_itemized, invoice_totals, inventory, departments
where invoice_itemized.invoice_number=invoice_totals.invoice_number
and year(invoice_totals.datetime)=2018 and month(invoice_totals.datetime)=10
and inventory.itemnum=invoice_itemized.itemnum
and inventory.dept_id=departments.dept_id
and departments.description<>'shop use'
and departments.description<>'none'
and departments.description<>'ingredients'
group by departments.description) t
) q1 on q1.[Total Profit] = q1.[Total Profit]
order by q.[Total Profit] desc

How to pick the 2 highest prices paid

This is the input data.
Dept Company Code Payment Amt
Gardeners Sort:Insurance Carrier 100 20.00
Gardeners Sort:Insurance Carrier 100 22.00
Gardeners Sort:Insurance Carrier 100 21.00
Gardeners Sort:Insurance Carrier 100 20.00
Gardeners Sort:Insurance Carrier 100 22.00
I want to return
Sort:Insurance Carrier 100 - 22.00 and 21.00
Not 22.00 and 22.00 I fear this code is returning 22 and 22 arguably the 2 top prices paid but not really so.
I have this SQL
SELECT
[DEPT], [Sort: Procedure Code] as Code, [Sort: Insurance Carrier],
SUM(CASE WHEN num = 1 THEN [Pmt Amount] ELSE 0 END) AS [first high],
SUM(CASE WHEN num = 2 THEN [Pmt Amount] ELSE 0 END) AS [second high]
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY
[DEPT], [Sort: Procedure Code], [Sort: Insurance Carrier]
ORDER BY [Pmt Amount] DESC) AS num,
[DEPT], [Sort: Procedure Code], [Sort: Insurance Carrier],
[Pmt Amount]
FROM
[revenuedetail$]
) AS t
WHERE num IN (1, 2)
GROUP BY [DEPT], [Sort: Procedure Code], [Sort: Insurance Carrier]
If you want the same value to have the same number, then you should use dense_rank() instead of row_number(). But you are on the right track!
Also change sum() to max() to avoid summing the values with the same dense_rank().
Try this:
select
[dept]
, [Sort: Procedure Code] as Code
, [Sort: Insurance Carrier]
, max(case when num = 1 then [Pmt Amount] else 0 end) as [first high]
, max(case when num = 2 then [Pmt Amount] else 0 end) as [second high]
from (
select
dense_rank() over(
partition by [dept], [Sort: Procedure Code], [Sort: Insurance Carrier]
order by [Pmt Amount] desc
) as num
, [dept]
, [Sort: Procedure Code]
, [Sort: Insurance Carrier]
, [Pmt Amount]
from [revenuedetail$]
) as t
where num in (1, 2)
group by [dept], [Sort: Procedure Code], [Sort: Insurance Carrier]
rextester demo: http://rextester.com/PJCDDC90476
returns:
+-----------+------+-------------------------+------------+-------------+
| dept | Code | Sort: Insurance Carrier | first high | second high |
+-----------+------+-------------------------+------------+-------------+
| Gardeners | 100 | Sort:Insurance Carrier | 22.00 | 21.00 |
+-----------+------+-------------------------+------------+-------------+
You seem to want dense_rank() rather than row_number():
SELECT [DEPT], [Sort: Procedure Code] as Code, [Sort: Insurance Carrier],
SUM(CASE WHEN num = 1 THEN [Pmt Amount] END) AS [first high],
SUM(CASE WHEN num = 2 THEN [Pmt Amount] END) AS [second high]
FROM (SELECT DENSE_RANK() OVER (PARTITION BY [DEPT], [Sort: Procedure Code], [Sort: Insurance Carrier]
ORDER BY [Pmt Amount] DESC
) AS num,
rd.*
FROM [revenuedetail$] rd
) rd
WHERE num IN (1, 2)
GROUP BY [DEPT], [Sort: Procedure Code], [Sort: Insurance Carrier];
Notes:
I removed the ELSE 0. If there is no second value, then this version returns NULL rather than 0. I find that more intuitive (add the ELSE 0 back if that is not the behavior you want).
I added more meaningful table aliases. rd makes more sense than t.
I used rd.* in the subquery. That actually shortens the query and makes it easier to modify.
You should reconsider your column names. All the square braces just make the code harder to write and to read.
If the sql server version is 2012 and above, Then Lead() can be used:
select Top 1 [DEPT], [Sort: Procedure Code], [Sort: Insurance Carrier],
[Pmt Amount] AS [first high],
Lead([Pmt Amount],1)over(partition by [DEPT], [Sort: Procedure Code],
[Sort: Insurance Carrier] ORDER BY [Pmt Amount] DESC)AS [Second high]
from [revenuedetail$] order by [Pmt Amount] desc

how to do the program using subquery approach

SELECT SKU, SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=6 AND STYPE='P'
THEN AMT
END) AS VALUEJUNE,
SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=7 AND STYPE='P'
THEN AMT
END) AS VALUEJULY,
SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=8 AND STYPE='P'
THEN AMT
END) AS VALUEAUGUST
,(VALUEJUNE+VALUEJULY+VALUEAUGUST) AS totalsales
FROM TRNSACT
GROUP BY SKU
ORDER BY totalsales DESC ;
Put most of your query in a derived table, including the GROUP BY. Calculate totalsales on its result:
select sku, VALUEJUNE, VALUEJULY, VALUEAUGUST, (VALUEJUNE+VALUEJULY+VALUEAUGUST) AS totalsales
from
(
SELECT SKU,
SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=6 AND STYPE='P'
THEN AMT
END) AS VALUEJUNE,
SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=7 AND STYPE='P'
THEN AMT
END) AS VALUEJULY,
SUM(CASE WHEN EXTRACT(MONTH FROM SALEDATE)=8 AND STYPE='P'
THEN AMT
END) AS VALUEAUGUST
FROM TRNSACT
GROUP BY SKU
) dt
ORDER BY totalsales DESC ;