Getting gender count from one table and inserting to another in Mysql - mysql

I am trying to take gender stats from table 1
table_1
and table 2
table_2
and insert into 'gender' table
gender
using the command :
INSERT INTO gender(Male) VALUES ((SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'),(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male'))
and
INSERT INTO gender(Female) VALUES ((SELECT COUNT(*) FROM table_1 WHERE Gender = 'Female'),(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Female'))
But i keep getting an error: Column count doesn't match value count at row 1

The number of values passed and the number columns in the gender table don't match, hence the error.
Assuming the table gender has following columns -> gender, count_1, count_2
INSERT INTO gender(gender, count_1, count_2) VALUES ('Male', (SELECT
COUNT() FROM table_1 WHERE Gender = 'Male'),(SELECT COUNT() FROM
table_2 WHERE Gender = 'Male'))
INSERT INTO gender(gender, count_1, count_2) VALUES ('Female', (SELECT
COUNT() FROM table_1 WHERE Gender = 'Female'),(SELECT COUNT() FROM
table_2 WHERE Gender = 'Female'))

The error is telling your insert expects rows with one column, but your value has two.
INSERT INTO gender(Male) VALUES ( -- start of a row
-- Column 1
(SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'),
-- Column 2
(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male')
) -- end of a row
The problem is you have an extra set of parens making it one row with two columns. If you want to insert two rows, remove those parens.
INSERT INTO gender(Male) VALUES
(SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'), -- row 1
(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male'); -- row 2
The parens go around each row.

Related

Not able to add multiple column against same ID in table

I have two tables x and y, x have the ID and many other columns, however y only have the ID similar as x table and then this ID is mapped to Many values
My Insert statement looks like this
INSERT INTO `table`
(`id`,
`other_name`)
VALUES
(select id from another_table where name = 'something'`,
('WALLETAB',
'SBTRADER',
'SBTRDACKING'));
expected result
1 | WALLETAB
1 | SBTRADER
1 | SBTRDACKING
I take ID from another table which already have data and this another table some different data associated with this table
You could fetch id from another table to be used in insert statement by using limit 1, something like:
select id from another_table where name = 'something' limit 1
However, to insert all 3 rows you will need a multiple insert in a single statement.
insert into `table` values
((select id from another_table where name = 'something' limit 1), 'WALLETAB'),
((select id from another_table where name = 'something' limit 1), 'SBTRADER'),
((select id from another_table where name = 'something' limit 1), 'SBTRDACKING');
See fiddle: https://www.db-fiddle.com/f/gYvrxdsDxVQPkZM2o8YRT1/1
It feels a lot of duplication. You can simplify it by either using variable or CTE. The following query utilizes CTE which only usable on mysql 8+:
insert into `table` (id, other_name)
with
other_id as (
select id from another_table where name = 'something'),
merged as (
select id, other_name from other_id join
(select 'WALLETAB' as other_name
union select 'SBTRADER'
union select 'SBTRDACKING')
as other_temp)
select * from merged;
The CTE above fetch the id on other_id. The union-select pairs is then used to create 3 rows containing 'WALLETAB', 'SBTRADER', and 'SBTRDACKING' respectively. Then both of them joined to get 3 rows with varying value on other_name but has id as 1.
See fiddle: https://www.db-fiddle.com/f/xgQta17bGphHAB81N2FNwX/1

Mysql insert a row only if id exist in another table

I have 2 simple table
table1 -> p_id | s_id
table2 -> p_id | s_id
The two table are same. The p_id ai value.
I would like to insert into the table2 a row, but **only if p_id is exist in table1. This is possible? (MySQL)
INSERT INTO table1 (p_id, s_id)
SELECT * FROM (SELECT '100', '2') AS tmp
WHERE NOT EXISTS (SELECT p_id FROM table2 WHERE p_id = '100')
LIMIT 1
You can insert into a table based on any SELECT query. For example:
INSERT INTO table2 (p_id, s_id)
SELECT p_id, 2 FROM table1 WHERE p_id = 100;
If there are zero rows in table1 with the specified p_id value, this is a no-op. That is, it inserts zero rows into table2. If there is 1 row in table1 with that p_id value, it inserts into table2.
No need for LIMIT 1 because if p_id is the primary key then there is guaranteed to be only 1 or 0 rows with the given value.
Try This
Insert into table2 (p_id,s_id) Select p_id,'2' as s_id FROM table1 where p_id=100 LIMIT 1

how to get the desired output in sql server 2008

Table Structure
EID COLA COLB
1 name A
1 age 23
1 city hyd
1 email abc#live.in
1 mobile 45126
2 name B
2 age 43
2 city bang
3 name C
3 age 13
3 city bang
3 email jdf#live.in
I would like to have the output as below
ID||COLA||COLB
1||name||A
1||age||23
1||city||hyd
1||email||abc#live.in
1||mobile||45126
2||name||B
2||age||43
2||city||bang
2||email||NULL
2||mobile||NULL
3||name||C
3||age||13
3||city||bang
3||email||jdf#live.in
3||mobile||NULL
Can you kindly let me know how to achieve this output.
how to display the result where any of the mandatory fields (name,age,city,email,mobile)are missing then it should display as that field as Null, in the query we would provide in the where clause by filtering a single id value and cola as (name,age,city,email,mobile)
my Query:
select
case colA
when cola then colA+'||'+colB
end
from tbl
where cola in ('name','age','city','email','mobile')
Let me start by saying that what you are asking would have been really easy if your table structure had required columns like name, age, city etc. Name Value Pair is not a good design for such tables, not to mention serious performance issues which will plague any solution against this structure.
Having said that, you can use either PIVOT / UNPIVOT or an Attribute table (a table containing list of attribute required) and GROUP BY with CROSS JOIN.
Sample Data
DECLARE #table1 TABLE(
EID INT, COLA VARCHAR(30), COLB VARCHAR(30) )
INSERT INTO #table1 VALUES
(1,'name','A'),
(1,'age','23'),
(1,'city','hyd'),
(1,'email','abc#live.in'),
(1,'mobile','45126'),
(2,'name','B'),
(2,'age','43'),
(2,'city','bang'),
(3,'name','C'),
(3,'age','13'),
(3,'city','bang'),
(3,'email','jdf#live.in');
Query using PIVOT / UNPIVOT
SELECT EID, COLA,NULLIF(COLB,'') COLB
FROM
(
SELECT EID,ISNULL([name],'') name,ISNULL([age],'') [age],ISNULL([city],'') [city],ISNULL([email],'') [email],ISNULL([mobile],'') [mobile]
FROM (SELECT EID,COLA,COLB
FROM #table1) T
PIVOT ( MAX(COLB) FOR COLA IN ( [name],[age],[city],[email],[mobile] ) ) AS pvt
) tbl
UNPIVOT (COLB FOR ColA IN (name,age,city,email,mobile)) AS Upvt
Notice that I am using ISNULL(col,'') because UNPIVOT excludes NULL values. If '' is a valid value for you, you can use another string to denote NULL or use the GROUP BY solution.
Query using Attribute table and GROUP BY with CROSS JOIN
;WITH Cols(Name) AS
(
SELECT 'name' UNION ALL SELECT 'age' UNION ALL SELECT 'city' UNION ALL SELECT 'email' UNION ALL SELECT 'mobile'
)
SELECT t.EID,C.Name,t1.COLB
FROM
(
SELECT EID
FROM #table1
GROUP BY EID
) t
CROSS JOIN Cols c
LEFT JOIN #table1 t1 ON t1.EID = t.EID and t1.COLA = C.Name
CREATE TABLE DesireOutput(EID nvarchar(10),COLA NVARCHAR(10),COLB nvarchar(50))
INSERT INTO DesireOutput VALUES ('1','name','A' )
INSERT INTO DesireOutput VALUES ('1','age','23')
INSERT INTO DesireOutput VALUES ('1','city','hyd')
INSERT INTO DesireOutput VALUES ('1','email','abc#live.IN')
INSERT INTO DesireOutput VALUES ('1','mobile','45126')
INSERT INTO DesireOutput VALUES ('2','name','B')
INSERT INTO DesireOutput VALUES ('2','age','43')
INSERT INTO DesireOutput VALUES ('2','city','bang')
INSERT INTO DesireOutput VALUES ('3','name','C')
INSERT INTO DesireOutput VALUES ('3','age','13')
INSERT INTO DesireOutput VALUES ('3','city','bang')
INSERT INTO DesireOutput VALUES ('3','email','jdf#live.IN')
DECLARE #t AS TABLE ( ColA NVARCHAR(50) )
INSERT INTO #t
SELECT DISTINCT
D.COLA
FROM DesireOutput D
SELECT t.EID , c.ColA , t1.COLB FROM ( SELECT
EID FROM DesireOutput GROUP BY EID
) t
CROSS JOIN #t c
LEFT JOIN DesireOutput t1 ON t1.EID = t.EID
AND t1.COLA = c.ColA ORDER BY EID

Insert data into table with result from another select query

I am seeking help on the following issue:
I have two tables
Table_1 columns are itemid, locationid, quantity
Table_2 columns are itemid, location1, location2, location3
I want to copy data from Table_1 (only quantity column) into Table_2 (into location1 column). The itemid are same in both the tables(Table_1 has duplicate item id's) so that's the reason I want to copy to a new table and keep all quantity in one single row with each location as a column. I am using the below query but it doesn't work
INSERT INTO
Table_2(location1)
(
SELECT qty
FROM Table_1
WHERE locationid = 1 AND Table_1.locationid = Table_2.locationid
)
If table_2 is empty, then try the following insert statement:
insert into table_2 (itemid,location1)
select itemid,quantity from table_1 where locationid=1
If table_2 already contains the itemid values, then try this update statement:
update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)
INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`)
SELECT sum(p1), sum(p2), sum(p3)
FROM `test`.`product`;
Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));

SQL. How to work/compare/find differences within different rows in the same table

I have a table which looks like this:
ID Date Size Marked
1 2010-02-02 2 X
2 2002-02-02 1
1 2010-02-03 2 X
2 2010-02-03 3
3 2010-02-03 4 X
And I have a code (PHP) which does following things:
a) Calculate sum of sizes per day
b) Find the difference between total for this day and last day.
c) Find the sum of sizes for rows which became marked this day (the row with the same id wasn't marked yesterday).
As example, I will get following results:
Date Total DiffWithYesterday MarkedThisDay
2010-02-02 3 0 0
2010-02-03 9 6 4
I have feeling that there is a way to write this in SQL. However I am quite weak in SQL, so I gave up after a day playing around inner joins, group by and embedded selects.
I would appreciate, if you give me some clues how to do that.
Oh.. And I am using MySQL.
Regards,
Victor
had fun with this one.
SELECT
today.date as Date,
today.total as Total,
(today.total - yesterday.total) as DiffWithYesterday ,
marked.total as MarkedThisDay
FROM
(SELECT date, sum(size) as total
FROM table_name
GROUP BY date) today
LEFT JOIN
(SELECT date, sum(size) as total
FROM table_name
WHERE marked = 'X'
GROUP BY date) marked ON today.date = marked.date
LEFT JOIN
(SELECT (date + INTERVAL 1 day) as date, sum(size) as total
FROM table_name
GROUP BY date) yesterday ON today.date=yesterday.date
obviously, you will need to replace "table_name" with the name of your table
Something like this works in SQL Server. I don't have MySQL to test but you can probably convert once you see the logic.
create table so (sodate datetime, sosize int, somarked varchar(1))
insert into so (sodate,sosize,somarked) values ('1-jan-2010',3,'X')
insert into so (sodate,sosize,somarked) values ('2-jan-2010',1,'X')
insert into so (sodate,sosize,somarked) values ('3-jan-2010',2,'X')
insert into so (sodate,sosize,somarked) values ('4-jan-2010',0,null)
insert into so (sodate,sosize,somarked) values ('5-jan-2010',2,null)
insert into so (sodate,sosize,somarked) values ('6-jan-2010',1,null)
insert into so (sodate,sosize,somarked) values ('6-jan-2010',4,null)
insert into so (sodate,sosize,somarked) values ('6-jan-2010',1,null)
insert into so (sodate,sosize,somarked) values ('7-jan-2010',3,'X')
insert into so (sodate,sosize,somarked) values ('8-jan-2010',3,'X')
insert into so (sodate,sosize,somarked) values ('9-jan-2010',2,null)
insert into so (sodate,sosize,somarked) values ('10-jan-2010',2,'X')
insert into so (sodate,sosize,somarked) values ('11-jan-2010',1,'X')
insert into so (sodate,sosize,somarked) values ('12-jan-2010',2,null)
insert into so (sodate,sosize,somarked) values ('13-jan-2010',3,'X')
select so.sodate
,sum(so.sosize) as Total
,isnull(sum(so.sosize),0) - isnull(min(so2.sosize),0) as DiffFromYesterday
,sum(case when so.somarked = 'X' then so.sosize end) as MarkedThisDay
from so
left join (select so.sodate,sum(so.sosize) sosize from so group by sodate) so2 on dateadd(dd,1,so2.sodate) = so.sodate
group by so.sodate
..and after installing mysql this seems to work there...
select so.sodate
,sum(so.sosize) as Total
,ifnull(sum(so.sosize),0) - ifnull(min(so2.sosize),0) as DiffFromYesterday
,sum(case when so.somarked = 'X' then so.sosize end) as MarkedThisDay
from so
left join (select so.sodate,sum(so.sosize) sosize from so group by sodate) so2 on (so2.sodate + INTERVAL 1 day )= so.sodate
group by so.sodate ;