SQL Query to GROUP BY using multiple WHERE values? - sql

I'm trying to show a simple table showing users in the database, but exclude users who returned items during a specified date range... For some reason I am stumped
SELECT Refunded, Product, COUNT(Amount) as Orders FROM `customer-data.all-users` WHERE Time BETWEEN '2023-01-01 00:00:00' AND '2023-01-25 00:00:00' AND Refunded = 'FALSE' GROUP BY Product

Related

Usage of two different timestamps in one SQL query

I am stuck on a SQL challenge:
Per day in 2019 the number of page visits and registrations
The dataset looks the following:
I don’t get how I can count both the number of page visits per day and the number of registrations per day as they are based on two different timestamps (users.user_registration_timestamp and informations.info_timestamp)? Do I need to use a subquery? And how would the SQL query look like?
You don't need a join, you just need to seperate Selects:
select cast(user_registration_timestamp as date), count(*)
from users
where user_registration_timestamp >= timestamp '2019-00-01 00:00:00'
and user_registration_timestamp < timestamp '2020-00-01 00:00:00'
group by cast(user_registration_timestamp as date)
union all
select cast(info_timestamp as date), count(*)
from informations
where info_timestamp >= timestamp '2019-00-01 00:00:00'
and info_timestamp < timestamp '2020-00-01 00:00:00'
group by cast(info_timestamp as date)
This returns two rows, if you want a single row CROSS JOIN both Selects.

SQL get distinct customer count by hour

I have two table with datein and timein that is recorded when an order is placed and another table with the column datepicked and timepicked that is recorded when the invoice from the order is picked up. I need to find out how many customer I have every hour, but some are placing order and some are picking up invoices and some are doing both. There could be more than one order and invoice for the same customer on the same day/hour.
OrderTable:
Ordernum
CustomerID
datein
timein
InvoiceTable:
CustomerID
InvoiceID
Ordernum
datepicked
timepicked
I tried this SQL, but I can't find out how to get the DISTINCT CUSTOMERID from both tables and the date and hours lined up on both tables, I noticed in the result if there was no order for one hour / day the columns did not lineup.
Select o.datein, i.datepicked, (o.datein) As iDay, HOUR(o.timein) as iH,
DayOfMonth(i.datepicked) As pDay, HOUR(i.timepicked) as pH, Count(*) as Total
from OrderTable o, InvoiceTable i
Where
o.datein >= '2019-01-01' and o.datein <= '2019-12-31'
GROUP BY o.datein, i.datepicked, iDay, iH, pDay, pH
Thanks for any help.
Kim
Not sure why the tables setup as they are, but if all you really care about is the DISTINCT customer per date/hour, I would do the following by pre-unioning just those records, then distinct count from that. Dont worry about joining if the transactions were done at separate times unless your consideration is that the order and invoice are BOTH handled within the same hour. What happens if one order is done at 10:59 and the invoice is 11:00 only 1 minute apart, but representative of 2 different hours. It would be the same 1 customer showing up in each individual hour component.
Notice the first "FROM" clause has a union to get all records to the same column name bulk of records, each of their own respective 2019 calendar activity date. Once that is done, get and group by for the COUNT DISTINCT customers.
select
AllRecs.DateIn,
hour( AllRecs.TimeIn ) ByHour,
DayOfMonth(AllRecs.DateIn) pDay,
Count( distinct AllRecs.CustomerID ) UniqueCustomers
from
( select
ot.CustomerID,
ot.datein,
ot.timein
from
OrderTable ot
where
ot.datein >= '2019-01-01'
and ot.datein <= '2019-12-31'
union all
select
it.CustomerID,
it.datepicked datein,
it.timepicked timein
from
InvoiceTable it
where
it.datepicked >= '2019-01-01'
and it.datepicked <= '2019-12-31' ) AllRecs
group by
AllRecs.DateIn,
hour( AllRecs.TimeIn ),
DayOfMonth(AllRecs.DateIn)
If you had a relation between these two tables it would be possible. If I understand what you are trying to do, InvoiceTable needs to be a child table of OrderTable with a foreign key field "OrderNum" that relates back to its parent "OrderTable" primary key "OrderNum". Therefore, you don't need a field "CusotmerID" on InvoiceTable and you would know when an Invoice been picked up belongs to an order from the same day.

How can I compare date results from duplicate item_number? I am looking for results that do not have a date before 09-30-2016

I have a table that contains transaction history, it time stamps a column each time the item number is sold. It looks like this:
What I need to do is determine which Item's have not had any transaction history since 2016-09-30.
I have tried this:
SELECT * FROM IVT_ITEMTRAN WHERE TRANS_DATE < '2016-09-30 00:00:00.000'
However the problem I run into with that is I am merely selecting every item with a timestamp before 2016-09-30.
How can I generate the results for items that have no history since the date I listed above?
Pretty sure this would do what you want.
SELECT *
FROM IVT_ITEMTRAN
WHERE ITEM_NUMBER NOT IN
(
SELECT ITEM_NUMBER
FROM IVT_ITEMTRAN
WHERE TRANS_DATE < '2016-09-30 00:00:00.000'
)
Or if you just want the ItemNumbers you could use some aggregation.
select ITEM_NUMBER
, EarliestDateSold = MIN(TRANS_DATE)
from IVT_ITEMTRAN
group by ITEM_NUMBER
having MIN(TRANS_DATE) > '2016-09-30 00:00:00.000'

How query works with missing Group by values

I am tryng to write a query to pull the total discount as well as revenue of my customer's orders by day. Note that for each ship_id there will be several items so I want to have the sum clauses as below and in the end, I have that group by and I want to group them by ship_id (this is unique for each order).
I got a result of 2M rows (this could be correct because we are a big) but I am not sure if my group by is correct. What if I only put ship_id there? How my query understands it?
d.ship_id
,to_char(d.order_datetime,'yyyy/mm/dd hh24:mi:ss') as datetime_order
,to_char(d.order_datetime, 'D') as day_order
,to_char(d.order_datetime, 'MM') as month_order
,sum(di.discount) as discount
,sum(di.price * di.units) AS price
FROM
table1 d
JOIN
table2 di
ON
d.ship_id = di.ship_id
GROUP BY
d.ship_id
,to_char(d.order_datetime,'yyyy/mm/dd hh24:mi:ss')
,to_char(d.order_datetime, 'D')
,to_char(d.order_datetime, 'MM')
In this query you grouping result by
ship_id (order)
d.order_datetime yyyy/mm/dd hh24:mi:ss (i think this is wrong if you need group only by day) this group is grouping by day,month,year,hour,minute and seconds
d.order_datetime 'D' (grouping by day correct)
d.order_datetime 'mm' (grouping by month correct, doesn't change results of grouping by day)
P.S.: I dont see grouping by costumer in anywhere.
Your query will sumarize all values groupped by itens on group by:
If you put, something like:
Select ship_id, ,sum(di.discount) as discount
,sum(di.price * di.units) AS price from table1 group by ship_id
The query will return Price and discount groupped by ship_id, when you make a group by you must put all non-*aggregate fields on group by.
*Aggregate funtions (Sum,AVG,count...)
Try explain better your problem to make me understand your situation(problem).

SQL for finding recently trending items

I have a table with the following data columns
date item
Every row is a transaction record of what item was bought on which date. How do I write a SQL to find the item that has gained most sales as a percentage over two time ranges. For example, to get at sales by items on a daily basis for a week, I can do
select
date,
item,
count(*)
from table
date >= '2012-01-01'
date <= '2012-01-07'
group by 1,2 order by 1
If I change the date range for the next week, I can get the items that sold on that week.
But I want to find a SQL solution to get this done in one pull without having to manipulate the data in Excel.
I always get this backwards the first time, but something like the below might get you started.
SELECT d1.item, COUNT(d1.item) / COUNT(d2.item) AS slope
FROM data AS d1
JOIN data AS d2 ON d2.item = d1.item
WHERE d1.date > '2012-01-01'
AND d2.date > '2012-01-07'
GROUP BY d1.item
ORDER BY COUNT(d1.item) / COUNT(d2.item) DESC
Have you tried this
select item
, 100 * count(*) / ( select count(*)
from table
where date between '2012-01-01' and '2012-01-07'
) as avrg
from table
where date between '2012-01-01' and '2012-01-07'
group by item
order by item