mysql adding data with special autoincrement - sql-insert

I have a question about how to add data in the table users_in_queue? I want to add data from another table but field number_in_queue must be like an autoincrement column for each queue_id. I mean that data in the table must have this structure:
user_id | queue_id | number_in_queue
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 1 | 3

The older version have to use some user variables to get to your result.
That is why it is quite ugly
CREATE Table user_in_queues(user_id INTEGER, queue_id INTEGER , number_in_queue INTEGER)
✓
INSERT INTO user_in_queues VALUES (1,1,0),(2,1,0),(3,2,0),(4,1,0),(5,2,0);
✓
SELECT * FROM user_in_queues;
user_id | queue_id | number_in_queue
------: | -------: | --------------:
1 | 1 | 0
2 | 1 | 0
3 | 2 | 0
4 | 1 | 0
5 | 2 | 0
SELECT
user_id, queue_id, number_in_queue
FROM
(SELECT
user_id,
IF(#queue = queue_id, #rn:=#rn + 1, #rn:=1) number_in_queue,
#queue:=queue_id queue_id
FROM
(SELECT
*
FROM
user_in_queues
ORDER BY queue_id , user_id) t1, (SELECT #queue:=0) t2, (SELECT #rn:=0) t3) t4
ORDER BY user_id;
user_id | queue_id | number_in_queue
------: | -------: | --------------:
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 1 | 3
5 | 2 | 2
UPDATE user_in_queues u
SET number_in_queue = (SELECT
number_in_queue
FROM
(SELECT
user_id,
IF(#queue = queue_id, #rn:=#rn + 1, #rn:=1) number_in_queue,
#queue:=queue_id queue_id
FROM
(SELECT
*
FROM
user_in_queues
ORDER BY queue_id , user_id) t1, (SELECT #queue:=0) t2, (SELECT #rn:=0) t3) t4
WHERE user_id = u.user_id AND queue_id = u.queue_id )
✓
SELECT * FROM user_in_queues;
user_id | queue_id | number_in_queue
------: | -------: | --------------:
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 1 | 3
5 | 2 | 2
db<>fiddle here

Related

Split column into different rows on SQLite recursively using delimiter ","

I have a SQLite table just like this:
the table name is 'surat'
But i want to make id_ayat to be split into different rows using SQLite query, and expected result just like this:
_id|id_surat|id_ayat
---+--------+-------
3 | 2 | 112
3 | 2 | 213
3 | 3 | 19
3 | 3 | 83
3 | 3 | 85
3 | 3 | 102
is that possible? what query that i can use in SQLite format?
With a recursive CTE:
with recursive cte as (
select _id, id_surat, id_ayat,
id_ayat + 0 col
from tablename
union all
select _id, id_surat, trim(substr(id_ayat, length(col) + 2)),
trim(substr(id_ayat, length(col) + 2)) + 0
from cte
where instr(id_ayat, ',')
)
select _id, id_surat, col id_ayat
from cte
order by _id, id_surat
See the demo.
Results:
| _id | id_surat | id_ayat |
| --- | -------- | ------- |
| 3 | 2 | 112 |
| 3 | 2 | 213 |
| 3 | 3 | 19 |
| 3 | 3 | 83 |
| 3 | 3 | 85 |
| 3 | 3 | 102 |

distinct values as new columns & count

I'm trying to generate a summary from a table using SQLite as below.
I need to aggregate 1) number of times each model was driven, 2) total distance driven & 3) get distinct values for driver col & count the number of times each driver has driven the particular model - GROUP BY modelwith COUNT(model) & SUM(distance) will help with 1 & 2 - `I need help with the last part #3 , what is the right approach to find number of occurrences for each distinct values of a column and add them as new columns for each model ?
My table is:
id model datetime driver distance
---|-----|------------|--------|---------
1 | S | 04/03/2009 | john | 399
2 | X | 04/03/2009 | juliet | 244
3 | 3 | 04/03/2009 | borat | 555
4 | 3 | 03/03/2009 | john | 300
5 | X | 03/03/2009 | juliet | 200
6 | X | 03/03/2009 | borat | 500
7 | S | 24/12/2008 | borat | 600
8 | X | 01/01/2009 | borat | 700
Result would be
id model| drives distance john juliet borat
---|-----|--------|---------|------|------ |------
1 | S | 2 | 999 | 1 | 0 | 1
2 | X | 4 | 1644 | 0 | 2 | 2
3 | 3 | 2 | 855 | 1 | 0 | 1
OK... this time I got it!
select new_table.model, count (new_table.model) as drives, sum (new_table.distance) as distance,
sum(case when driver = 'john' then 1 else 0 end) as john,
sum(case when driver = 'juliet' then 1 else 0 end) as juliet,
sum(case when driver = 'borat' then 1 else 0 end) as borat
from new_table
group by model
It's not 100%, but this should get you most of the way there.
CREATE TABLE DBO.TEST_TABLE (ID INT,MODEL CHAR(1),DATETIME VARCHAR(255),DRIVER VARCHAR(255),DISTANCE INT)
INSERT INTO DBO.TEST_TABLE
VALUES
(1,'S','04/03/2009','JOHN',399)
,(2,'X','04/03/2009','JULIET',244)
,(3,'3','04/03/2009','BORAT',555)
,(4,'3','03/03/2009','JOHN',300)
,(5,'X','03/03/2009','JULIET',200)
,(6,'X','03/03/2009','BORAT',500)
,(7,'S','24/12/2008','BORAT',600)
,(8,'X','01/01/2009','BORAT',700)
Declare #Query_ nvarchar(MAX)
Declare #Cols_For_Pivot_ nvarchar(MAX)
SELECT #Cols_For_Pivot_= COALESCE(#Cols_For_Pivot_ + ',','') + QUOTENAME(DRIVER)
FROM (SELECT DISTINCT DRIVER FROM DBO.TEST_TABLE) AS PivotTable
IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL DROP TABLE #TEMP
SET #Query_ =
N'SELECT DISTINCT
MODEL
,COUNT(DATETIME) OVER(PARTITION BY MODEL) AS DRIVES
,SUM(DISTANCE) OVER(PARTITION BY MODEL) AS DISTANCE
, ' + #Cols_For_Pivot_ + '
INTO #TEMP
FROM DBO.TEST_TABLE
PIVOT(COUNT(DRIVER)
FOR DRIVER IN (' + #Cols_For_Pivot_ + ')) AS P'
EXEC sp_executesql #Query_

SQLite compare query from 2 tables

I would like to create a new query for know how many product are in the store.
table: tb_store
+--------+------------+------------------+-----------+
| item_id| nome | data_out | data_in |
+--------+------------+------------------+-----------+
| 1 | Produ1 | null | 2015-01-06|
| 2 | Produ1 | null | 2015-01-06|
| 3 | Produ3 | null | 2015-01-06|
| 4 | Produ3 | null | 2015-01-06|
| 5 | Produ5 | null | 2015-01-06|
| 6 | Produ4 | 2015-01-06 | 2015-02-06|
| 7 | Produ2 | 2015-01-06 | 2015-02-06|
+--------+------------+------------------+-----------+
table: tb_product
+--------+------------+
| item_id| nome |
+--------+------------+
| 1 | Produ1 |
| 2 | Produ2 |
| 3 | Produ3 |
| 4 | Produ4 |
| 5 | Produ5 |
+--------+------------+
i have write this query:
select nome, count(nome) as pezzi from tb_store where data_out is null or data_out="" group by nome order by pezzi desc
the result are:
+--------+------------+
| nome | pezzi |
+--------+------------+
| Produ1 | 2 |
| Produ3 | 2 |
| Produ5 | 1 |
+--------+------------+
i would like to obtain this result:
+--------+------------+
| nome | pezzi |
+--------+------------+
| Produ1 | 2 |
| Produ3 | 2 |
| Produ5 | 1 |
| Produ2 | 0 |
| Produ4 | 0 |
+--------+------------+
is possible? how can rewrite the query?
EDIT
I have create a new query like this:
SELECT DISTINCT nome, pezzi FROM(
SELECT nome,COALESCE(pezzi,0)as pezzi FROM(
SELECT p.nome, COUNT(s.nome) as pezzi
FROM tb_product as p LEFT JOIN tb_store as s
ON p.nome = s.nome
WHERE s.data_out is null
OR s.data_out = ""
GROUP BY p.nome
union
select nome,null as pezzi from tb_product) )
ORDER BY pezzi DESC
but i have some duplicate item to remove....the result is
nome pezzi
crema 2
pistacchio 2
zabajone 2
bacio 1
cassata 1
cioccolato 1
ciocco rum 1
malaga 1
mango 1
mascarpone 1
nocciola 1
stracciatella 1
bacio 0
caramello 0
cassata 0
cioccolato 0
ciocco rum 0
crema 0
fragola 0
limone 0
malaga 0
mango 0
mascarpone 0
nocciola 0
pistacchio 0
zabajone 0
is possible to remove the duplicate that are 0?
SELECT DISTINCT nome, pezzi FROM(
SELECT nome,COALESCE(pezzi,0)as pezzi FROM(
SELECT p.nome, COUNT(s.nome) as pezzi
FROM tb_product as p LEFT JOIN tb_store as s
ON p.nome = s.nome
WHERE s.data_out is null
OR s.data_out = ""
GROUP BY p.nome
union
select nome,null as pezzi from tb_product) GROUP BY nome )
ORDER BY pezzi DESC
You need to do a left join between the two tables like:
SELECT p.nome, COUNT(s.nome) as pezzi
FROM tb_product as p LEFT JOIN tb_store as s
ON p.name = s.name
WHERE data_out is null
OR data_out = ""
GROUP BY p.nome
ORDER BY pezzi DESC

distinct sum does not distinct values

I have 2 tables, reservations and articles:
Reservations
------------------------------
Id | Name | City |
------------------------------
1 | Mike | Stockholm
2 | Daniel | Gothenburg
2 | Daniel | Gothenburg
3 | Andre | Gothenburg (Majorna)
Articles
-------------------------------------------------------------
ArticleId | Name | Amount | ReservationId |
-------------------------------------------------------------
10 | Coconuts | 1 | 1
10 | Coconuts | 4 | 2
11 | Apples | 2 | 2
12 | Oranges | 2 | 3
I want to select Articles Name and the sum of Articles.Amount per Articles.ArticleId and Reservations.City.
My code:
SELECT distinct r.ID,a.Name as ArticleName,
sum(a.Amount) as ArticlesAmount,
substr(r.City,1,3) as ToCityName
FROM Reservations r
INNER JOIN Articles a
on r.Id = a.ReservationId
WHERE a.Name <> ''
GROUP BY ToCityName,a.ArticleId,a.Name
ORDER BY ToCityName ASC
This gives me following result:
Id | ArticleName | ArticlesAmount | ToCityName
2 | Coconuts | 8 | Got
2 | Apples | 4 | Got
3 | Oranges | 2 | Got
1 | Coconuts | 1 | Sto
But i want:
Id | ArticleName | ArticlesAmount | ToCityName
2 | Coconuts | 4 | Got
2 | Apples | 2 | Got
3 | Oranges | 2 | Got
1 | Coconuts | 1 | Sto
Help would be appreciated, and an explanation please :)
Fiddle
Have a look at SQLFiddle
Code:
SELECT distinct r.ID,a.Name as ArticleName,
sum(distinct a.Amount) as ArticlesAmount,
substr(r.City,1,3) as ToCityName
FROM Reservations r
INNER JOIN Articles a
on r.Id = a.ReservationId
WHERE a.Name <> ''
GROUP BY ToCityName,a.ArticleId,a.Name
ORDER BY ToCityName ASC
You want to ensure you sum the amount by the distinct number of times it appears per group.
I had added Articles again to select requested rows again... here is query
SELECT DISTINCT
r.ID,
a.`Name` AS ArticleName,
Articles.Amount,
substr(r.City, 1, 3) AS ToCityName
FROM
Reservations r
INNER JOIN Articles a ON r.Id = a.ReservationId
INNER JOIN Articles ON a.ReservationId = Articles.ReservationId
AND a.ArticleId = Articles.ArticleId
WHERE
a. NAME <> ''
GROUP BY
ToCityName,
a.ArticleId,
a. NAME
ORDER BY
ToCityName ASC

how to sum the column and get the rows based on month and year

It is my table can i get result for this .
Each user have points,i have to show number of user points got in current month,current year
Thanks.
--------------------------------
| userId | points | date |
--------------------------------
| 1 | 5 | 8/25/2013 |
| 1 | 3 | 8/16/2013 |
| 1 | 2 | 8/01/2013 |
| 1 | 2 | 9/25/2013 |
| 1 | 5 | 8/25/2013 |
| 1 | 3 | 2/16/2012 |
| 2 | NULL | NULL |
| 2 | NULL | NULL |
--------------------------------
They result should be like :
---------------------------------------------------
| userId | CurrentMonthpoints | CurrentYearPoints |
---------------------------------------------------
| 1 | 15 | 17 |
| 2 | NULL | NULL |
---------------------------------------------------
My request :
SELECT userId,
(SELECT sum(points)
from tbl_points
WHERE PointsDate between '8/1/2013' and '8/31/2013') AS CurrentMonthPoints,
(SELECT distinct SUM(points)
from tbl_points
WHERE PointsDate between '1/1/2014' and '12/31/2014' ) AS CurrentYearPoints
from tbl_user_performance_points
But My query shows wrongly as :
---------------------------------------------------
| userId | CurrentMonthpoints | CurrentYearPoints |
---------------------------------------------------
| 1 | 15 | 17 |
| 2 | 15 | 17 |
---------------------------------------------------
Advance Thanks
Give this a try:
select a.userID,
a.points_sum_m as currentmonthpoints,
b.points_sum_y as currentyearpoints
from (select userID, sum(points) as points_sum_m
from tbl_points
where month(date) = month(getdate())
group by userID) a
inner join (select userID, sum(points) as points_sum_y
from tbl_points
where year(date) = year(getdate())
group by userID) b
on a.userID = b.userID;
SQLFiddle: http://sqlfiddle.com/#!3/ff780/12
with month_cte(userid,Current_Month) as
(select userid,sum(Points)Current_Month from tbl_points
where datepart(mm,PointsDate)=datepart(mm,getdate()) and datepart(YY,PointsDate)=datepart(yy,getdate()) group by userid)
, year_cte(userid,Current_year) as
(select userid,sum(Points)Current_Year from tbl_points
where datepart(YY,PointsDate)=datepart(yy,getdate()) group by userid)
select Distinct t.Userid, Current_Month, Current_Year From tbl_points T
left join month_cte mc on T.userid=mc.userid
left join year_cte yc on t.userid=yc.userid
if you just want to correct your query replace it with this...
SELECT userId,
(SELECT sum(points)
from tbl_points
WHERE PointsDate between '8/1/2013' and '8/31/2013' and userId= X.UserId) AS CurrentMonthPoints,
(SELECT distinct SUM(points)
from tbl_points
WHERE PointsDate between '1/1/2014' and '12/31/2014' and userId = X.UserId) AS CurrentYearPoints
from tbl_user_performance_points X

Resources