Trying to get data for every 6 months - sql

I am running SQL Server and trying to get data for every 6 months.
Here is my query but it is for year, I want it to be every 6 months:
SELECT
DISTINCT YEAR(datein) AS 'Year',
COUNT(*) AS 'Total'
FROM
users
GROUP BY
YEAR(datein)
I want the column value should appear as: MONTH/YEAR

Use month() or quarter() and some arithmetic. Here is one way:
select YEAR(datein) as Year, FLOOR((MONTH(datein) - 1) / 6) as Year_Part,
COUNT(*) as Total
from users
group by YEAR(datein), FLOOR((MONTH(datein) - 1) / 6);
Or, you can put this into two columns:
select year(datein) as year,
sum(case when month(datein) <= 6 then 1 else 0 end) as total_half_1,
sum(case when month(datein) > 6 then 1 else 0 end) as total_half_2
from users
group by year(datein)
order by year(datein);

Related

SQL query select returns different result than expected

I'm querying on this 2 tables:
TIMBRATURE
ASSELEMGEN
This is my query:
select convert(varchar(11),convert(date,datav),105) as data,
sum (CASE WHEN idterminale=3 and DATEPART(hour,datav)>='9' and DATEPART(hour,datav)<='16' THEN 1 ELSE 0 END) as pranzoP,
sum (CASE WHEN idterminale=3 and DATEPART(hour,datav)>='17' and DATEPART(hour,datav)<='23' THEN 1 ELSE 0 END) as cenaP,
sum (CASE WHEN idterminale=3 THEN 1 ELSE 0 END) as totaleP
from TIMBRATURE where DATAV>=#dataDa and DATAV<#primoGGmeseSuccessivo and TIMBRATURE.IDDIP
in (select iddip from ASSELEMGEN where IDELEM=1001)
group by convert(date,datav)
order by convert(date,datav)
For this purpose consider this argumets:
declare #datada as date='20230201'
declare #primoggmesesuccessivo as date='20230207'
The result I get:
Iddip is user ID, problem is when user have 2 entries for the same day, one with datav hour part between 9 and 16, the other between 17 and 23. In this case I have to count 2 for it, but my query only count it once. For example in the result above on 1th February I expect PranzoP=93 and totaleP=130.

Combine 2 queries together

I am struggling to work out combining a query that should give me 3 columns of Month, total_sold_products and drinks_sold_products
Query 1:
Select month(date), count(id) as total_sold_products
from Products
where date between '2022-01-01' and '2022-12-31'
Query 2
Select month(date), count(id) as drinks_sold_products
from Products where type = 'drinks' and date between '2022-01-01' and '2022-12-31'
I tried the union function but it summed count(id) twice and gave me only 2 columns
Many thanks!
Union is for attaching sets of data on top of each other. You need conditional aggregation or a join. See below.
SELECT MONTH(date),
COUNT(*) AS total_sold_products,
COUNT(CASE WHEN type = 'drinks' THEN 1 ELSE 0 END) AS drinks_sold_products,
FORMAT((CASE
WHEN COUNT(*) > 0 THEN
COUNT(CASE WHEN type = 'drinks' THEN 1 ELSE 0 END)/COUNT(*)
ELSE 0 END),
'P') AS Percentage
FROM Products
WHERE date BETWEEN'2022-01-01' AND '2022-12-31'
GROUP BY MONTH(date)

Turning PIVOT query into table function

Following up on BigQuery pivot on more fields, based on the suggestion by the genius Mikhail, I was wondering if the following 'pivot-like functionality' could be turned into a table function. Here would be an example:
The query from the currently accepted answer is:
select
(case when grp_set & 1 > 0 then Reseller end) as Reseller,
(case when grp_set & 2 > 0 then ProductGroup end) as ProductGroup,
(case when grp_set & 4 > 0 then Product end) as Product,
(case when grp_set & 8 > 0 then Year end) as Year,
(case when grp_set & 16 > 0 then Quarter end) as Quarter,
(case when grp_set & 32 > 0 then Product_Info end) as Product_Info,
sum(Revenue) as Revenue,
sum(Units) as Units
from `first-outlet-750.biengine_tutorial.Product`, unnest(generate_array(1, 64)) grp_set
where Year IN (2020) and Quarter in ('Q1', 'Q2')
group by 1, 2, 3, 4, 5, 6
having not (Quarter is null and Product_Info is not null)
and not (Year is null and Quarter is not null)
and not (ProductGroup is null and Product is not null)
order by 1, 2, 3, 4 , 5, 6
And I'm wondering if a table function could be created along the lines of:
PIVOT(
[row_agg1, row_agg2, ...],
[col_agg1, col_agg2, ...],
[agg_val1, agg_val2, ...]
)
So the above query could hopefully be translated into something like:
SELECT
*
FROM
PIVOT(
[Reseller, ProductGroup, Product], -- rows
[Year, Quarter, ProductInfo], -- cols
[SUM(Revenue), SUM(Units)] -- vals
)
A few things that I think might be a bit tricky:
Where does the actual table go in the FROM clause?
How would aliases work? For example, what if we wanted SUM(Revenue) to show up as TotalRev -- how to easily be able to refer to that in the main SELECT clause to be able to alias it if not just doing a SELECT * ?

How can I count total number of sales per month using a condition in SQL?

I searched the forum but couldn't find a problem like the one I have. I have a table called Journal Table and it has the following data:
A transaction is considered to be sales if the Quantity>0 otherwise it's a loan transaction. Now my question is how can I count the total number of transactions as Sales Per month.
Like:
Month | TotalSales
1 5
2 3
3 7
I tried the following but got the wrong output:
Select DISTINCT Month(date) AS 'Month',
(Select COUNT(TransactionID) from journalTable where Quantity>0)
AS 'Total Sales' from journalTable;
Here is a picture of the output:
The output is wrong as it counts the total of all months and shows it for each month. It should count each month's total and show it.
Just group by and conditionally sum.
select Month(date) as 'Month'
, sum(case when Quantity > 0 then 1 else 0 end) as 'Total Sales'
-- You can even add a count of loans at the same time.
, sum(case when Quantity <= 0 then 1 else 0 end) as 'Total Loans'
from journalTable
group by Month(date);
Something like this
SELECT MONTH(DATE) AS MONTH, COUNT(QUANTITY)CNTT
FROM TRANSACTIONS
WHERE QUANTITY > 0
GROUP BY MONTH(DATE)

Query to show all months and show values where there are data for the corresponding months

I have a query and it shows the months where there is corresponding data. However, I would like to show all of the months in the year and have the months where there are no data shown as zero.
There is my SQL Statement:
SELECT DATENAME(MONTH, hb_Disputes.OPENED) AS MonthValue,
COUNT(CASE WHEN REV_CLS = 2 THEN 1 END) AS SmallCommercialIndust,
COUNT(CASE WHEN REV_CLS <> 2 THEN 1 END) AS Residential
FROM hb_Disputes
WHERE (hb_Disputes.ASSGNTO = 'E099255') AND (YEAR(hb_Disputes.OPENED) = YEAR(GETDATE()))
GROUP BY hb_Disputes.OPENED
And this is my output:
I also have a table name MonthName that shows all of the months in a year and I know I may need to use this to accomplish what I'm trying to achieve but I'm not sure how to get there:
If you have data in the table for all months, but the where clause is filtering it out, then the simplest method is to extend the conditional aggregation:
SELECT DATENAME(MONTH, d.OPENED) AS MonthValue,
SUM(CASE WHEN d.ASSGNTO = 'E099255' AND d.REV_CLS = 2 THEN 1 ELSE 0 END) AS SmallCommercialIndust,
SUM(CASE WHEN d.ASSGNTO = 'E099255' AND d.REV_CLS <> 2 THEN 1 ELSE 0 END) AS Residential
FROM hb_Disputes d
WHERE YEAR(d.OPENED) = YEAR(GETDATE())
GROUP BY DATENAME(MONTH, d.OPENED)
ORDER BY MIN(d.OPENED);
Note: This does not fix the issue in all cases. It should just be a simple way to modify your query -- and will often work.