Group By with Case Statements SQL Server - sql

I would like to group by with the case statements in SQL Server. I created cases that's my revenue range. I'd like to calculate the number of sales orders within all these revenue ranges(cases)
Below please find my queries:
Select
sum(OrderQuantity) as Orders,
case when (sum(SalesAmount-TaxAmt-Freight)<100 and sum(SalesAmount-TaxAmt-Freight)>=0) then '$0-$100'
when (sum(SalesAmount-TaxAmt-Freight)>=100 and sum(SalesAmount-TaxAmt-Freight)<500) then '$100-$500'
when (sum(SalesAmount-TaxAmt-Freight)>=500 and sum(SalesAmount-TaxAmt-Freight)<1000) then '$500-$1000'
when (sum(SalesAmount-TaxAmt-Freight)>=1000 and sum(SalesAmount-TaxAmt-Freight)<2500) then '$1000-$2500'
when (sum(SalesAmount-TaxAmt-Freight)>=2500 and sum(SalesAmount-TaxAmt-Freight)<5000) then '$2500-$5000'
when (sum(SalesAmount-TaxAmt-Freight)>=5000 and sum(SalesAmount-TaxAmt-Freight)<10000) then '$5000-$10000'
when (sum(SalesAmount-TaxAmt-Freight)>=10000 and sum(SalesAmount-TaxAmt-Freight)<50000) then '$10000-$50000'
when (sum(SalesAmount-TaxAmt-Freight)>=50000 and sum(SalesAmount-TaxAmt-Freight)<100000) then '$50000-$100000'
when (sum(SalesAmount-TaxAmt-Freight)>=100000) then '>$100000'
end as SalesAmountCategory
From
dbo.FactResellerSales
group by
SalesAmountCategory;
I expect to get the result like:
result example
I keep getting errors when i try to group by based on the case statements. The error is "Invalid column name 'SalesAmountCategory'". How can i do that? Many thanks in advance!

It looks like you want to know number of orders in each category
So, you need first to map each order to category and then group by it, like that:
select SalesAmountCategory, count(*) from
(
Select case
when ((SalesAmount-TaxAmt-Freight)>=100000) then '>$100000'
when ((SalesAmount-TaxAmt-Freight)>=50000) then '$50000-$100000'
when ((SalesAmount-TaxAmt-Freight)>=10000) then '$10000-$50000'
when ((SalesAmount-TaxAmt-Freight)>=5000) then '$5000-$10000'
when ((SalesAmount-TaxAmt-Freight)>=2500) then '$2500-$5000'
when ((SalesAmount-TaxAmt-Freight)>=1000) then '$1000-$2500'
when ((SalesAmount-TaxAmt-Freight)>=500) then '$500-$1000'
when ((SalesAmount-TaxAmt-Freight)>=100) then '$100-$500'
when ((SalesAmount-TaxAmt-Freight)<100) then '$0-$100'
end as SalesAmountCategory
From dbo.FactResellerSales
) as t
group by SalesAmountCategory

Related

BigQuery Query working with multiple "likes" but not working with "in"

I would like to isolate some emails with specific titles. I can use multiple "like"s connected with an ORs in the where clause. This gives me a number of results. However, if I try to do a ____ in ('____', '____', etc), the code suddenly returns nothing.
This does not work.
select DATE_TRUNC(DATE(send_time,"America/Los_Angeles"), week(monday)) as week,
status,
settings_title,
sum(emails_sent) as emails_sent,
sum(report_summary_opens) as report_summary_opens,
sum(report_summary_unique_opens) as report_summary_unique_opens,
sum(report_summary_subscriber_clicks) as report_summary_subscriber_clicks
from mailchimp.campaigns_view
where status = 'sent'
and settings_title in ('%_LL_%', '%_IC_%', '%_AC_%', '%_CC_%', '%_PC_%')
group by 1,2,3
order by 1 desc
However, this works.
select DATE_TRUNC(DATE(send_time,"America/Los_Angeles"), week(monday)) as week,
status,
settings_title,
sum(emails_sent) as emails_sent,
sum(report_summary_opens) as report_summary_opens,
sum(report_summary_unique_opens) as report_summary_unique_opens,
sum(report_summary_subscriber_clicks) as report_summary_subscriber_clicks
from mailchimp.campaigns_view
where status = 'sent'
and (settings_title like '%_LL_%'
or settings_title like '%_IC_%'
or settings_title like '%_AC_%'
or settings_title like '%_CC_%'
or settings_title like '%_PC_%')
group by 1,2,3
order by 1 desc
I have already tried to include a subquery in my "from" that eliminates all null settings_title. Any ideas why this is not working? Am I missing some small syntax error?
Thanks for the help!
The % symbol will only work with LIKE. For IN it's only equality. Try REGEXP_CONTAINS too.
As in:
SELECT REGEXP_CONTAINS("abcdefg", '(xxx|zzz|yyy|cd)')
Thanks Felipe, very usefull!!!. In my case I used REGEXP_CONTAINS for matching with a multiple patterns added to a table. The select with the column "pattern_str" located in the second position is able to search and find correctly for every portion of the parttern:
WITH CTE_PatternCovid as (
Select STRING_AGG(Pattern,'|') as strPattern from xxxxxxxxx.TEMP.Temp_patternsearch_covid 
)
--this convert the multiple patterns into a single line:
--.*MASK.FFP.|.*MASK.KN.|.*TEST.ANTIG.|.*MASK.QUI.|.*SP.*H.DRO.AL.
--then use in this way:
Select ProductName FROM xxxxxxxxx.TEMP.Table_ProductsName_covid 
where
regexp_contains (upper(ProductName),(SELECT strPattern FROM CTE_PatternCovid ))

Getting a query result taken from the same data but with temporary var

I got a simple thing to do.
Well, maybe not, but someone somewhere surely can help me out : P
I got a simple data structure that contains
expedition date
delivery date
transaction type
I would need to create a query which could
order the rows by a date specific to the transaction type.
(ie : using the expedition date for transaction of type "selling", and delivery date for transaction of type "purchasing")
I was wondering if there was a more efficient way to do this than
by fetching 2 times the same data with different clause where(while adding a column used to order them(tempDate)) and then using another select to encompass these 2 queries to which I would add the order clause on the tempDate.
--> the initial fetching I would do 2 times works on many tables(many, many, many joins)
Basically my current solution is :
Select * from
(
Select ...
date_exp as dateTemp;
from ...
where conditions* And dateRelatedCondition
UNION
Select ...
date_livraison as dateTemp;
from ...
Where conditions* And NOT(dateRelatedCondition)
) as comboSelect
Order By MIN(comboSelect.dateTemp)
OVER(PARTITION BY(REF_product)),
(REF_product),
comboSelect.dateTemp asc;
*
->Those conditions are the same in both inner Select query
Thank you for your time.
Without the UNION:
dateRelatedCondition should be removed from WHERE and put to the SELECT like:
CASE WHEN dateRelatedCondition THEN date_exp ELSE date_livraison END as dateTemp
Without the subquery:
in ORDER BY you need the same expression in the window function:
Order By MIN(CASE WHEN dateRelatedCondition THEN date_exp ELSE date_livraison END)
OVER(PARTITION BY(REF_product)),
(REF_product),
dateTemp asc
You mean like this?:
ORDER BY CASE
WHEN TransactionType = 'Selling' THEN ExpeditionDate
WHEN TransactionType = 'purchasing' THEN DeliveryDate
END

"Your query does not include the specified expression..."

I have tried endless things to get this to work and it seems to break over and over again and not work. I'm trying to GROUP BY product after I have calculated the field quantity returned/quantity ordered, but I get the error
your query does not include the specified expression 'quantity_returned/quantity_ordered' as part of an aggregate function.
I do not want to GROUP BY quantity_returned, quantity_ordered, and product, I only want to GROUP BY product.
Here's what my SQL looks like currently...
SELECT
quantity_returned/quantity_ordered AS percentage_returned,
quantity_returned,
quantity_ordered,
returns_fact.product
FROM
Customer_dimension
INNER JOIN
(
Product_dimension
INNER JOIN
(
Day_dimension
INNER JOIN
returns_fact
ON Day_dimension.day_key = returns_fact.day_key
)
ON Product_dimension.product_key = returns_fact.product_key
)
ON Customer_dimension.customer_key = returns_fact.customer_key
GROUP BY returns_fact.product;
When you use a group by you need to actually include everything in your select that isn't a aggregate function.
I have no idea how your tables are set up, but I am throwing a blind dart. If you provide fields in each of the 4 tables someone will be better able to help.
SELECT returns_fact.product, count(quantity_returned), count(quantity_ordered), count(quantity_returned)/count(quantity_ordered) as percentage returned

SQL Error - not a group by expression

With this SQL Query, I am attempting to list overdue book by patron. In addition, I want to group and order the books by patron. I understand you have to use some kind of aggregate function when doing a GROUP BY function. Even so, I am getting a "not a group by expression" error. Any help is appreciated.
Edit: updated code
What if I want to get the total fees per person and book? The bottom code is still resulting in the same error.
SELECT PATRON.LAST_NAME, PATRON.FIRST_NAME, PATRON.PHONE, BOOK.BOOK_TITLE, CHECKOUT.DUE_DATE, SUM((SYSDATE - CHECKOUT.DUE_DATE) * 1.00) AS FEE_BALANCE
FROM CHECKOUT
JOIN PATRON
ON CHECKOUT.PATRON_ID=PATRON.PATRON_ID
JOIN COPY
ON CHECKOUT.COPY_ID=COPY.COPY_ID
JOIN BOOK
ON COPY.BOOK_ID=BOOK.BOOK_ID
WHERE CHECKOUT.RETURN_DATE IS NULL
AND CHECKOUT.DUE_DATE > SYSDATE
GROUP BY PATRON.PATRON_ID
HAVING SUM((SYSDATE - CHECKOUT.DUE_DATE) > 0
ORDER BY PATRON.LAST_NAME, PATRON.FIRST_NAME;
You need to add these 3 columns to the GROUP BY clause...
PATRON.PHONE, BOOK.BOOK_TITLE, CHECKOUT.DUE_DATE
So it would be...
SELECT
PATRON.LAST_NAME,
PATRON.FIRST_NAME,
PATRON.PHONE,
BOOK.BOOK_TITLE,
CHECKOUT.DUE_DATE,
SUM((SYSDATE - CHECKOUT.DUE_DATE) * 1.00) AS BALANCE
FROM CHECKOUT
JOIN PATRON
ON CHECKOUT.PATRON_ID=PATRON.PATRON_ID
JOIN COPY
ON CHECKOUT.COPY_ID=COPY.COPY_ID
JOIN BOOK
ON COPY.BOOK_ID=BOOK.BOOK_ID
WHERE CHECKOUT.RETURN_DATE IS NULL
AND CHECKOUT.DUE_DATE > SYSDATE
GROUP BY PATRON.LAST_NAME, PATRON.FIRST_NAME, PATRON.PHONE, BOOK.BOOK_TITLE, CHECKOUT.DUE_DATE
ORDER BY PATRON.LAST_NAME, PATRON.FIRST_NAME
Bottom line is, if you have a GROUP BY clause, you can only select columns that are part of the GROUP BY unless you are using some kind of scalar value function on them, like COUNT, SUM, MAX, MIN, etc.
Otherwise if you aren't grouping or using a scalar-value function, multiple rows could have different values for that column, so what would the query results be?

Sql sum and show result in many column

If I have a table look like in this page and I wanna sum the orderPrice by each customer.
Then I wanna show the result show in one row look like this.
How can I write the query.
Ps. Sorry for show everything on web.
Since you did not put any restrictions on how that information should be produced, you can do the following:
Select Sum( Case When Customer = 'Hansen' Then OrderPrice End ) As sumHansen
, Sum( Case When Customer = 'Nilsen' Then OrderPrice End ) As sumNilsen
, Sum( Case When Customer = 'Jensen' Then OrderPrice End ) As sumJensen
From CustomerTotals
If your'e using SQL Server you can use PIVOT statement.