SQL Get the total count of registered user in day by day - mysql

Can you help me to construct a query. The scenario is this, I want to get the total value of the registered users each day.

Select count(*)
from tableName
Where registered = true
Group by Date

Assuming that your registration timestamp is stored at created_at date-time field and table named say user:
SELECT created_at,COUNT(*) as `total registration` FROM `user` GROUP BY (DATE(`user`.`created_at`))

The former answers do neither cover the where part nor output the dayname.
This should do both and produce what you want:
create table #data (
reg_id int,
reg_email nvarchar(255),
reg_date datetimeoffset(7)
)
insert into #data(reg_id, reg_email, reg_date)
VALUES
(1, 'a', '2018-10-01'),
(2, 'b', '2018-10-01'),
(3, 'c', '2018-10-02'),
(4, 'd', '2018-10-03'),
(5, 'e', '2018-10-01'),
(6, 'f', '2018-10-02'),
(7, 'g', '2018-10-04'),
(8, 'h', '2018-10-05'),
(9, 'i', '2018-10-05'),
(10, 'j', '2018-10-06')
SELECT count(*), datename(dw, reg_date) from #data
where datepart(week, reg_date) = 40
group by reg_date
drop table #data
assuming that you are using sql server greater or equal 2008!

I finally get the correct data for today and last 7 days. Please refer below query.
SELECT
a.JourneyName,
a.BonusName,
a.Status,
a."Timestamp",
a.MID,
COUNT(CASE WHEN DATEDIFF(DD, a."Timestamp", GETDATE()) = 0 THEN 1 ELSE NULL END) as "Day_1",
COUNT(CASE WHEN DATEDIFF(DD, a."Timestamp", GETDATE()) = 1 THEN 1 ELSE NULL END) as "Day_2",
COUNT(CASE WHEN DATEDIFF(DD, a."Timestamp", GETDATE()) = 2 THEN 1 ELSE NULL END) as "Day_3",
COUNT(CASE WHEN DATEDIFF(DD, a."Timestamp", GETDATE()) = 3 THEN 1 ELSE NULL END) as "Day_4",
COUNT(CASE WHEN DATEDIFF(DD, a."Timestamp", GETDATE()) = 4 THEN 1 ELSE NULL END) as "Day_5",
COUNT(CASE WHEN DATEDIFF(DD, a."Timestamp", GETDATE()) = 5 THEN 1 ELSE NULL END) as "Day_6",
COUNT(CASE WHEN DATEDIFF(DD, a."Timestamp", GETDATE()) = 6 THEN 1 ELSE NULL END) as "Day_7"
FROM
TableName a
WHERE
a."Timestamp" >= DATEADD(DD, -7, GETDATE())
AND a."Timestamp" <= GETDATE()
GROUP BY``
a.JourneyName, a.BonusName, a.Status, a."Timestamp", a.MID
Total Count per day where Day_1 is today, Day_2 is yesterday and so on.

Related

Is it possible to fetch needed data in one query?

I have a database containing tickets. Each ticket has a unique number but this number is not unique in the table. So for example ticket #1000 can be multiple times in the table with different other columns (Which I have removed here for the example).
create table countries
(
isoalpha varchar(2),
pole varchar(50)
);
insert into countries values ('DE', 'EMEA'),('FR', 'EMEA'),('IT', 'EMEA'),('US','USCAN'),('CA', 'USCAN');
create table tickets
(
id int primary key auto_increment,
number int,
isoalpha varchar(2),
created datetime
);
insert into tickets (number, isoalpha, created) values
(1000, 'DE', '2021-01-01 00:00:00'),
(1001, 'US', '2021-01-01 00:00:00'),
(1002, 'FR', '2021-01-01 00:00:00'),
(1003, 'CA', '2021-01-01 00:00:00'),
(1000, 'DE', '2021-01-01 00:00:00'),
(1000, 'DE', '2021-01-01 00:00:00'),
(1004, 'DE', '2021-01-02 00:00:00'),
(1001, 'US', '2021-01-01 00:00:00'),
(1002, 'FR', '2021-01-01 00:00:00'),
(1005, 'IT', '2021-01-02 00:00:00'),
(1006, 'US', '2021-01-02 00:00:00'),
(1007, 'DE', '2021-01-02 00:00:00');
Here is an example:
http://sqlfiddle.com/#!9/3f4ba4/6
What I need as output is the number of new created tickets for each day, devided into tickets from USCAN and rest of world.
So for this Example the out coming data should be
Date | USCAN | Other
'2021-01-01' | 2 | 2
'2021-01-02' | 1 | 3
At the moment I use this two queries to fetch all new tickets and then add the number of rows with same date in my application code:
SELECT MIN(ti.created) AS date
FROM tickets ti
LEFT JOIN countries ct ON (ct.isoalpha = ti.isoalpha)
WHERE ct.pole = 'USCAN'
GROUP BY ti.number
ORDER BY date
SELECT MIN(ti.created) AS date
FROM tickets ti
LEFT JOIN countries ct ON (ct.isoalpha = ti.isoalpha)
WHERE ct.pole <> 'USCAN'
GROUP BY ti.number
ORDER BY date
but that doesn't look like a very clean method. So how can I improved the query to get the needed data with less overhead?
Ii is recommended that is works with mySQL 5.7
You may logically combine the queries using conditional aggregation:
SELECT
MIN(CASE WHEN ct.pole = 'USCAN' THEN ti.created END) AS date_uscan,
MIN(CASE WHEN ct.pole <> 'USCAN' THEN ti.created END) AS date_other
FROM tickets ti
LEFT JOIN countries ct ON ct.isoalpha = ti.isoalpha
GROUP BY ti.number
ORDER BY date;
You can create unique entries for each date/country then use that value to count USCAN and non-USCAN
SELECT created,
SUM(1) as total,
SUM(CASE WHEN pole = 'USCAN' THEN 1 ELSE 0 END) as uscan,
SUM(CASE WHEN pole != 'USCAN' THEN 1 ELSE 0 END) as nonuscan
FROM (
SELECT created, t.isoalpha, MIN(pole) AS pole
FROM tickets t JOIN countries c ON t.isoalpha = c.isoalpha
GROUP BY created,isoalpha
) AS uniqueTickets
GROUP BY created
Results:
created total uscan nonuscan
2021-01-01T00:00:00Z 4 2 2
2021-01-02T00:00:00Z 3 1 2
http://sqlfiddle.com/#!9/3f4ba4/45/0
Regarding the answer of SQL Hacks I found the right solution
SELECT created,
SUM(1) as total,
SUM(CASE WHEN pole = 'USCAN' THEN 1 ELSE 0 END) as uscan,
SUM(CASE WHEN pole != 'USCAN' THEN 1 ELSE 0 END) as nonuscan
FROM (
SELECT created, t.isoalpha, MIN(pole) AS pole
FROM tickets t JOIN countries c ON t.isoalpha = c.isoalpha
GROUP BY t.number
) AS uniqueTickets
GROUP BY SUBSTR(created, 1 10)

select sum until a specific line is found

CREATE TABLE Coins (Badge VARCHAr(10), Cointype INT, Number INT);
INSERT INTO Coins (Badge,Cointype, Number) VALUES
('' , 1, 1),
('' , 5, 2),
('' , 20, 3),
('' , 1, 4),
('' , 5, 5),
('' , 5, 6),
('' , 5, 7),
('RESET', 0 , 0),
('' , 1, 8),
('' , 10, 9),
('RESET', 0 , 0),
('' , 5, 10),
('' , 20, 11);
Hi, with this table I want to have the following sum above the first line ('RESET',0,0)
select
SUM(case when Cointype=1 Then Number else 0 END) as SUM1,
SUM(case when Cointype=5 Then Number else 0 END) as SUM5,
SUM(case when Cointype=20 Then Number else 0 END) as SUM20
from Coins
result must be this:
SUM1 SUM5 SUM20
5 20 3
Is this possible in MySql?
in the real situation, there is also an ID and timestamp field. the top record is the most recent record with the highest ID and timestamp.
So the most recent records must summarized until the RESET line. (in case we need ordering, this is possible with the ID or timestamp field)
Then the table is like this:
CREATE TABLE Coins (ID INT, Badge VARCHAr(10), Cointype INT, Number INT);
INSERT INTO Coins (ID, Badge,Cointype, Number) VALUES
(13,'' , 1, 1),
(12,'' , 5, 2),
(11,'' , 20, 3),
(10,'' , 1, 4),
(9,'' , 5, 5),
(8,'' , 5, 6),
(7,'' , 5, 7),
(6,'RESET', 0 , 0),
(5,'' , 1, 8),
(4,'' , 10, 9),
(3,'RESET', 0 , 0),
(2,'' , 5, 10),
(1,'' , 20, 11);
If you have an autonumeric column:
SQL DEMO
select
SUM(case when Cointype=1 Then Number else 0 END) as SUM1,
SUM(case when Cointype=5 Then Number else 0 END) as SUM5,
SUM(case when Cointype=20 Then Number else 0 END) as SUM20
from Coins
WHERE ID < ( SELECT MIN(ID)
FROM Coins
WHERE Badge = 'RESET' )
OUTPUT
| SUM1 | SUM5 | SUM20 |
|------|------|-------|
| 5 | 20 | 3 |
EDIT:
After you change your sample looks like you have the rows in inverse order. Then you need MAX() instead of MIN()
select
SUM(case when Cointype=1 Then Number else 0 END) as SUM1,
SUM(case when Cointype=5 Then Number else 0 END) as SUM5,
SUM(case when Cointype=20 Then Number else 0 END) as SUM20
from Coins
WHERE ID > ( SELECT MAX(ID)
FROM Coins
WHERE Badge = 'RESET' )

Case in where condition to calculate individual totals

select
Count(*)
from gl
join TRVMAINDATA msit
on gl.TRANSACTIONID = msit.CHARGETRANSACTIONID
where gl.CREATEDDATETIME >= DATEADD(MONTH,-2,getdate()) AND
datediff(DAY,gl.BUSINESSPROCESSDATE,gl.CREATEDDATETIME)>=4 AND
gl.MARKETCODE In('535','532','056','050','039','036','034','033','030','029','027','023','022','021','018','015','012','011','010','009','007','006','005','002','001' ) and DATEADD(MONTH,DATEDIFF(MONTH,0,gl.CREATEDDATETIME),0) = '2/1/2017 12:00:00 AM'
The above code gives the total for market code mentioned.
But i also want the market code for other code which doesn't belog here. for example
select
Count(*)
from gl
join TRVMAINDATA msit
on gl.TRANSACTIONID = msit.CHARGETRANSACTIONID
where gl.CREATEDDATETIME >= DATEADD(MONTH,-6,getdate()) AND
datediff(DAY,gl.BUSINESSPROCESSDATE,gl.CREATEDDATETIME)>=0
and
DATEADD(MONTH,DATEDIFF(MONTH,0,gl.CREATEDDATETIME),0) = '2/1/2017 12:00:00 AM'
AND
(case
when gl.MARKETCODE In('535','532','056','050','039','036','034','033','030','029','027','023','022','021','018','015','012','011','010','009','007','006','005','002','001') then 'Proprietary'
when gl.MARKETCODE='037' then 'US'
else 'partner'
end )
Is it possible to calculate totals of other market codes in one sql query or do i have to calculate individually?
I think you would like to do count with case when in select statement like this:
SELECT COUNT(CASE
WHEN gl.marketcode IN ( '535', '532', '056', '050',
'039', '036', '034', '033',
'030', '029', '027', '023',
'022', '021', '018', '015',
'012', '011', '010', '009',
'007', '006', '005', '002', '001' ) THEN 1
ELSE NULL
END) AS `Proprietary`,
COUNT(CASE
WHEN gl.marketcode = '037' THEN 1
ELSE NULL
END) AS `US`,
COUNT(CASE
WHEN gl.marketcode NOT IN ( '535', '532', '056', '050',
'039', '036', '034', '033',
'030', '029', '027', '023',
'022', '021', '018', '015',
'012', '011', '010', '009',
'007', '006', '005', '002',
'001', '037' ) THEN 1
ELSE NULL
END) AS `partner`
FROM gl
JOIN trvmaindata msit
ON gl.transactionid = msit.chargetransactionid
WHERE gl.createddatetime >= DATEADD(month, -2, GETDATE())
AND DATEDIFF(day, gl.businessprocessdate, gl.createddatetime) >= 4
AND DATEADD(month, DATEDIFF(month, 0, gl.createddatetime), 0) = '2/1/2017 12:00:00 AM'

Stored Procedure Throws Error, but running as a query does not

I am aggregating data for reporting, and have a stored procedure that I am trying to insert into a temporary table. If I just run EXEC <stored_proc_name> it works just fine. However, when I try and run the following code:
Create table #TempResults2
(
slscode varchar(3),
intakes_this_month int,
intakes_this_year int,
intakes_last_month int,
intakes_two_months int,
intakes_three_months int,
intakes_four_months int,
intakes_five_months int,
intakes_six_months int,
ships_this_month int,
ships_last_month int,
ships_two_months int,
ships_three_months int,
ships_four_months int,
ships_five_months int,
ships_six_months int,
ships_this_year int
PRIMARY KEY CLUSTERED (SLSCODE)
)
INSERT INTO #TempResults2
EXEC crm.dbo.sp_sales_info
SELECT * FROM #TempResults2
DROP TABLE #TempResults2
I get the following error:
Msg 8114, Level 16, State 1, Procedure sp_sales_info, Line 36
Error converting data type varchar to int.
Warning: Null value is eliminated by an aggregate or other SET operation.
Here is my stored procedure, and I know the problem is somewhere in the first section (where I get all the shipping information) because I can comment that out and just select the intake stuff and the temp table thing works:
UPDATE here is the full stored proc
ALTER PROCEDURE [dbo].[sp_sales_info]
-- Add the parameters for the stored procedure here
AS
BEGIN
DECLARE
#today date, #this_month date, #last_month_start date, #last_month_end date,
#two_months_start date, #two_months_end date, #three_months_start date, #three_months_end date,
#four_months_start date, #four_months_end date, #five_months_start date, #five_months_end date,
#six_months_start date, #six_months_end date, #this_year_start date, #startdate date, #enddate date;
SET #today = GETDATE();
SET #this_month = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0);
SET #last_month_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -1, 0);
SET #last_month_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -1 + 1, 0));
SET #two_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -2, 0);
SET #two_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -2 + 1, 0));
SET #three_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -3, 0);
SET #three_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -3 + 1, 0));
SET #four_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -4, 0);
SET #four_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -4 + 1, 0));
SET #five_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -5, 0);
SET #five_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -5 + 1, 0));
SET #six_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -6, 0);
SET #six_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -6 + 1, 0));
SET #this_year_start = CAST(DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) as DATE);
SET #startdate = DATEADD(YEAR, -1, GETDATE());
SET #enddate = #today;
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
a.*,
d.intakes_this_month,
d.intakes_last_month,
d.intakes_two_months,
d.intakes_three_months,
d.intakes_four_months,
d.intakes_five_months,
d.intakes_six_months,
d.intakes_this_year
FROM
(
SELECT
sum(CASE WHEN a.SHIPDATE >= #this_month THEN 1 ELSE 0 END) AS ships_this_month,
sum(CASE WHEN a.SHIPDATE BETWEEN #last_month_start AND #last_month_end THEN 1 ELSE 0 END) AS ships_last_month,
sum(CASE WHEN a.SHIPDATE BETWEEN #two_months_start AND #two_months_end THEN 1 ELSE 0 END) AS ships_two_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #three_months_start AND #three_months_end THEN 1 ELSE 0 END) AS ships_three_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #four_months_start AND #four_months_end THEN 1 ELSE 0 END) AS ships_four_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #five_months_start AND #five_months_end THEN 1 ELSE 0 END) AS ships_five_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #six_months_start AND #six_months_end THEN 1 ELSE 0 END) AS ships_six_months,
sum(CASE WHEN a.SHIPDATE >= #this_year_start THEN 1 ELSE 0 END) AS ships_this_year,
b.slcode
FROM
(
SELECT
A.ACCOUNT AS CODE,
MIN(CAST(A.BILLDATETIME AS DATE)) AS SHIPDATE
FROM PACWARE.ADS.ARODME A
LEFT OUTER JOIN PACWARE.ADS.PTDME B ON A.PTCODE=B.CODE_
LEFT OUTER JOIN event.dbo.newdate() D ON A.ACCOUNT=D.ACCOUNT
LEFT OUTER JOIN event.dbo.newdate_extras() D2 ON A.ACCOUNT=D2.ACCOUNT
WHERE A.BILLDATETIME>=#startdate
AND A.BILLDATETIME<=#enddate
AND (
(D.NEWDATE>=#startdate AND D.NEWDATE<=#enddate) OR
(D2.NEWDATE IS NOT NULL AND D2.NEWDATE>=#startdate AND D2.NEWDATE<=#enddate) OR
B.MEDICAREID='L7900'
)
AND B.MEDICAREID IN ('A4253','L7900','A9276')
AND A.CATEGORY<>'ID'
Group by
A.ACCOUNT,
B.MEDICAREID,
A.CATEGORY
) a
JOIN event.dbo.patient_dg() b on a.CODE = b.code
GROUP BY b.slcode
) a
JOIN (
SELECT
sum(CASE WHEN a.regdate >= #this_month THEN 1 ELSE 0 END) AS intakes_this_month,
sum(CASE WHEN a.regdate BETWEEN #last_month_start AND #last_month_end THEN 1 ELSE 0 END) AS intakes_last_month,
sum(CASE WHEN a.regdate BETWEEN #two_months_start AND #two_months_end THEN 1 ELSE 0 END) AS intakes_two_months,
sum(CASE WHEN a.regdate BETWEEN #three_months_start AND #three_months_end THEN 1 ELSE 0 END) AS intakes_three_months,
sum(CASE WHEN a.regdate BETWEEN #four_months_start AND #four_months_end THEN 1 ELSE 0 END) AS intakes_four_months,
sum(CASE WHEN a.regdate BETWEEN #five_months_start AND #five_months_end THEN 1 ELSE 0 END) AS intakes_five_months,
sum(CASE WHEN a.regdate BETWEEN #six_months_start AND #six_months_end THEN 1 ELSE 0 END) AS intakes_six_months,
sum(CASE WHEN a.regdate >= #this_year_start THEN 1 ELSE 0 END) AS intakes_this_year,
a.slscode
FROM
event.dbo.patient_dg_lite() a
GROUP BY a.slscode
) d on a.slcode = d.slscode
JOIN event.dbo.employee_slscode b on a.slcode = b.slscode
JOIN event.dbo.employee c on b.employee_id = c.id
END
Your columns aren't in the same ordinal positions slscode is defined first in the CREATE TABLE.
Create table #TempResults2
(
slscode varchar(3),
/*Rest of table*/
ships_this_year int
)
But your SELECT in the stored procedure has it as the last column
SELECT
/* Loads of CASE statements*/
b.slcode
FROM /* ... */
So you are trying to insert the slscode varchar column into the integer ships_this_year column

Group by, with rank and sum - not getting correct output

I'm trying to sum a column with rank function and group by month, my code is
select dbo.UpCase( REPLACE( p.Agent_name,'.',' '))as Agent_name, SUM(convert ( float ,
p.Amount))as amount,
RANK() over( order by SUM(convert ( float ,Amount )) desc ) as arank
from dbo.T_Client_Pc_Reg p
group by p.Agent_name ,p.Sale_status ,MONTH(Reg_date)
having [p].Sale_status='Activated'
Currently I'm getting all total value of that column not month wise
Name amount rank
a 100 1
b 80 2
c 50 3
for a amount 100 is total amount till now but , i want get current month total amount not last months..
Maybe you just need to add a WHERE clause? Here is a minor re-write that I think works generally better. Some setup in tempdb:
USE tempdb;
GO
CREATE TABLE dbo.T_Client_Pc_Reg
(
Agent_name VARCHAR(32),
Amount INT,
Sale_Status VARCHAR(32),
Reg_date DATETIME
);
INSERT dbo.T_Client_Pc_Reg
SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'NotActivated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()-40;
Then the query:
SELECT
Agent_name = UPPER(REPLACE(Agent_name, '.', '')),
Amount = SUM(CONVERT(FLOAT, Amount)),
arank = RANK() OVER (ORDER BY SUM(CONVERT(FLOAT, Amount)) DESC)
FROM dbo.T_Client_Pc_Reg
WHERE Reg_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
AND Reg_date < DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)
AND Sale_status = 'Activated'
GROUP BY UPPER(REPLACE(Agent_name, '.', ''))
ORDER BY arank;
Now cleanup:
USE tempdb;
GO
DROP TABLE dbo.T_Client_Pc_Reg;