How can I group_concat this mysql fields - mysql

I have this MySQL Query:
SELECT a.orcidid
, GROUP_CONCAT(distinct a.`from` SEPARATOR '<>' ) as StartDate
, GROUP_CONCAT(distinct a.`to` SEPARATOR '<>' ) as EndDate
from orcidaffils a
GROUP BY a.orcidid ;
For this DATA Table:
CREATE TABLE `orcidaffils` (
`recid` int(11) NOT NULL AUTO_INCREMENT,
`affil` varchar(6000) DEFAULT NULL,
`orcidid` varchar(100) DEFAULT NULL,
`city` varchar(100) DEFAULT NULL,
`country` varchar(100) DEFAULT NULL,
`from` date DEFAULT NULL,
`to` date DEFAULT NULL,
PRIMARY KEY (`recid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of orcidaffils
-- ----------------------------
INSERT INTO `orcidaffils` VALUES ('2', 'Graz University of Technology', '0000-0004-1034-5187', 'Graz', 'AT', '2010-01-01', null);
INSERT INTO `orcidaffils` VALUES ('3', 'Ecole Polytechnique', '0000-0004-1034-5187','Palaiseau', 'FR', '2008-09-01', '2010-07-01');
INSERT INTO `orcidaffils` VALUES ('4', 'University of Würzburg', '0000-0004-1034-5187', 'Wurzburg', 'DE', '2005-09-01', '2007-12-01');
No I would like to get this output:
The question is how to group_concat that the beginndate and the enddate is merged together per affliliation.
2010-01-01-now<>2008-01-09 to 2010-01-07<>2005-01-09 to 2007-01-12
thanks for any usefull advice.

As per the image you've mentioned
you could try something like this:
SELECT a.orcidid ,
GROUP_CONCAT(a.`affil` SEPARATOR '<>' )
, GROUP_CONCAT(CONCAT(a.`from`, ' to ', IFNULL(a.`to`,'now')) SEPARATOR '<>' ) AS StartDate
FROM orcidaffils a
GROUP BY a.orcidid ;

Related

SQL query not returning correct result using three table together?

I have 3 tables in which tbl_user_signup_info, tbl_main_lead_info and tbl_campaign_info, I need a result in which it display info such that each row display the lead id and campaign id added by corresponding registered users of the tbl_user_signup_info and display should be like User_Id, Lead_Id, Campaign_ID.
Actually i want Total number of leads added by particular user with there Lead Id and Total number of campaign added by that user with there Campaign_Id using those 3 tables.
But i am lacking to form SQL query.
My Result are as below which are wrong:
Table structure
--
-- Table structure for table `tbl_campaign_info`
--
DROP TABLE IF EXISTS `tbl_campaign_info`;
CREATE TABLE IF NOT EXISTS `tbl_campaign_info` (
`Campaign_Id` int(100) NOT NULL AUTO_INCREMENT,
`CampaignName` varchar(200) NOT NULL,
`CampaignStatus` varchar(200) NOT NULL,
`CampaignDescription` varchar(200) DEFAULT NULL,
`CampaignOwnerNotes` varchar(200) DEFAULT NULL,
`CampaignAdminNotes` varchar(200) DEFAULT NULL,
`CampaignStartDate` date NOT NULL,
`CampaignEndDate` date NOT NULL,
`CampaignLead_Id` int(100) NOT NULL,
`CampaignAddedBy` int(100) NOT NULL,
`CampaignAddedOn` date DEFAULT NULL,
UNIQUE KEY `Campaign_Id` (`Campaign_Id`)
) ENGINE=MyISAM AUTO_INCREMENT=18 DEFAULT CHARSET=latin1;
--
-- Table structure for table `tbl_main_lead_info`
--
DROP TABLE IF EXISTS `tbl_main_lead_info`;
CREATE TABLE IF NOT EXISTS `tbl_main_lead_info` (
`Lead_Id` int(100) NOT NULL AUTO_INCREMENT,
`FirstName` varchar(100) DEFAULT NULL,
`LastName` varchar(100) DEFAULT NULL,
`Company` varchar(100) DEFAULT 'NA',
`Website` varchar(100) DEFAULT 'NA',
`Designation` varchar(100) DEFAULT 'NA',
`Linkedin` varchar(100) DEFAULT 'NA',
`Email` varchar(100) DEFAULT NULL,
`Phone` varchar(100) DEFAULT NULL,
`State` varchar(100) DEFAULT NULL,
`Country` varchar(100) DEFAULT NULL,
`TechArea` varchar(100) DEFAULT NULL,
`FirmType` varchar(100) DEFAULT NULL,
`FirmSize` varchar(100) DEFAULT NULL,
`LastContactDate` date DEFAULT NULL,
`NextContactDate` date DEFAULT NULL,
`LeadDescription` varchar(200) DEFAULT NULL,
`OwnerNotes` varchar(200) DEFAULT NULL,
`SetReminder` date DEFAULT NULL,
`AdminNotes` varchar(200) DEFAULT NULL,
`LeadStatus` varchar(100) DEFAULT NULL,
`LeadAddedBy` int(100) NOT NULL,
`LeadAddedOn` datetime DEFAULT NULL,
PRIMARY KEY (`Lead_Id`),
UNIQUE KEY `FirstName` (`FirstName`,`LastName`,`Company`,`Website`,`Designation`,`Linkedin`,`Email`,`Phone`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tbl_main_lead_info`
--
INSERT INTO `tbl_main_lead_info` (`Lead_Id`, `FirstName`, `LastName`, `Company`, `Website`, `Designation`, `Linkedin`, `Email`, `Phone`, `State`, `Country`, `TechArea`, `FirmType`, `FirmSize`, `LastContactDate`, `NextContactDate`, `LeadDescription`, `OwnerNotes`, `SetReminder`, `AdminNotes`, `LeadStatus`, `LeadAddedBy`, `LeadAddedOn`) VALUES
(15, 'John', 'Doe', 'test', 'test', 'test', 'test', 'test', 'test', 'Texas', 'USA', 'test', 'Corporate', '11-50', '2020-01-09', '2020-01-10', 'Testing Description of Lead information', NULL, '2020-01-11', 'This need to be confidential by admin', 'Active', 18, '2020-01-09 16:07:17');
--
-- Dumping data for table `tbl_campaign_info`
--
INSERT INTO `tbl_campaign_info` (`Campaign_Id`, `CampaignName`, `CampaignStatus`, `CampaignDescription`, `CampaignOwnerNotes`, `CampaignAdminNotes`, `CampaignStartDate`, `CampaignEndDate`, `CampaignLead_Id`, `CampaignAddedBy`, `CampaignAddedOn`) VALUES
(16, 'Test', 'Active', 'Test', NULL, 'This is admin notes and need to be kept confidential', '2020-01-09', '2020-01-10', 15, 18, '2020-01-09'),
(17, 'Test', 'Active', 'Test ', NULL, 'NA', '2020-01-10', '2020-01-10', 15, 18, '2020-01-09');
--
-- Table structure for table `tbl_user_signup_info`
--
DROP TABLE IF EXISTS `tbl_user_signup_info`;
CREATE TABLE IF NOT EXISTS `tbl_user_signup_info` (
`User_Id` int(50) NOT NULL AUTO_INCREMENT,
`UserEmail` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`UserName` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`UserPassword` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`Admin` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`User_Id`) USING BTREE,
UNIQUE KEY `Email` (`UserEmail`),
UNIQUE KEY `UserName` (`UserName`),
UNIQUE KEY `UserEmail` (`UserEmail`,`UserName`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `tbl_user_signup_info`
--
INSERT INTO `tbl_user_signup_info` (`User_Id`, `UserEmail`, `UserName`, `UserPassword`, `Admin`) VALUES
(18, 'test#gmail.com', 'test', 'test', 1),
(22, 'test1#gmail.com', 'test1', 'test1', 0),
(23, 'test2#gmail.com', 'test2', 'test2', 0);
COMMIT;
and My SQl Query is as below:
SELECT User_Id, Campaign_Id, Lead_Id
FROM tbl_campaign_info AS C,
tbl_main_lead_info AS M,
tbl_user_signup_info AS U
WHERE C.CampaignAddedBy IN ( SELECT User_Id
FROM tbl_user_signup_info AS U,
tbl_campaign_info AS C
WHERE U.User_Id = C.CampaignAddedBy)
AND M.LeadAddedBy IN (SELECT User_Id
FROM tbl_user_signup_info AS U,
tbl_main_lead_info AS M
WHERE U.User_Id = M.LeadAddedBy )
If I understand correctly, you want users campaign counts and lead counts per user. So, select campaign counts, select lead counts, join them.
You could use a full outer join of the two results for this (thus getting only those users that have at least one campain or lead), but MySQL doesn't support it. I take it that tbl_user_signup_info contains one row per user, though, so you can use this as a base table. The following query gives you a result for every user in that table.
select
u.user_id,
coalesce(c.total, 0) as campaign_count,
coalesce(l.total, 0) as lead_count
from tbl_user_signup_info u
left join
(
select campaignaddedby, count(*) as total
from tbl_campaign_info
group by campaignaddedby
) c on c.campaignaddedby = u.user_id
left join
(
select leadaddedby, count(*) as total
from tbl_main_lead_info
group by leadaddedby
) l on l.leadaddedby = u.user_id
order by u.user_id;
It seems like you can only use JOIN.
SELECT U.User_Id, Campaign_Id, Lead_Id
FROM tbl_user_signup_info AS U
JOIN tbl_campaign_info AS C ON U.User_Id = C.CampaignAddedBy
JOIN tbl_main_lead_info AS M ON U.User_Id = M.LeadAddedBy
Actually i want Total number of leads added by particular user with
there Lead Id and Total number of campaign added by that user with
there Campaign_Id using those 3 tables.
Try this:
SELECT
X.USER_ID,
X.LeadCount,
IF(Y.LEAD_ID IS NULL, 0, Y.LEAD_ID) LEAD_ID,
IF(Y.CampaignCount IS NULL, 0, Y.CampaignCount) CampaignCount
FROM (
SELECT
U.User_ID, COUNT(DISTINCT LEAD_ID) LeadCount
FROM
tbl_user_signup_info U
LEFT JOIN
tbl_main_lead_info M
ON (U.User_Id = M.LeadAddedBy)
GROUP BY
U.USER_ID
) X
LEFT JOIN
(
SELECT
M.LeadAddedBy, M.LEAD_ID, COUNT(DISTINCT Campaign_Id) CampaignCount
FROM
tbl_campaign_info C
LEFT JOIN
tbl_main_lead_info M
ON (C.CampaignAddedBy = M.LeadAddedBy)
GROUP BY
M.LeadAddedBy, M.LEAD_ID
) Y
ON (
X.USER_ID = Y.LeadAddedBy
)
SQL Fiddle link: http://sqlfiddle.com/#!9/4e138/40

Sql query - Cant select the max value of a row

I have this query that showing items in my site.
$sql = "
select p.id
, p.name
, p.logo
, p.short_description
, c.Parent_category
, IF(d.commission_name = 'percent'
, CONCAT(FORMAT(d.action, 2)/2 ,' %')
, CONCAT(FORMAT(d.action,2)/2,' €')) as comms
, GROUP_CONCAT(c.category_name SEPARATOR ',') as category_names
from eshop p
join eshop_cat c
on p.id = c.eshop_id
join eshop_commissions d
on p.id = d.eshop_id
where c.Parent_category = 'fashion'
and p.sites = 1
GROUP
BY d.action DESC
";
The problem is here
IF(d.commission_name = 'percent', CONCAT(FORMAT(d.action, 2)/2 ,' %') ,
CONCAT(FORMAT(d.action,2)/2,' €'))
i need only the biggest value of each eshop id. i tryied with this
IF(d.commission_name = 'percent', CONCAT(FORMAT(max(d.action), 2)/2 ,' %') ,
CONCAT(FORMAT(max(d.action),2)/2,' €'))
but its not working
For example i have 2 entries with the same eshop id
How can i receive only 1 commission that will be the biggest?
eshop_id commission_name action
1 percent 20 (%)
1 fixed_amount 30 (euro)
EDITED
CREATE TABLE `eshop` (
`id` int(11) NOT NULL,
`name` text NOT NULL,
`logo` text NOT NULL,
`short_description` text NOT NULL,
`sites` tinyint(1) NOT NULL,
`url` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`summary` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `eshop_commissions` (
`commission_name` text NOT NULL,
`eshop_id` int(11) NOT NULL,
`action` decimal(10,2) NOT NULL,
`subaction` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `eshop_cat` (
`eshop_id` int(11) NOT NULL,
`category_name` text NOT NULL,
`Parent_category` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `eshop_commissions` (`commission_name`, `eshop_id`, `action`, `subaction`) VALUES
('percent', 100, '12.00', '12.00'),
('fixed_amount', 100, '15.00', '15.00'),
('percent', 100, '5.00', '5.00'),
('percent', 100, '2.00', '2.00');
INSERT INTO `eshop` (`id`, `name`, `logo`, `short_description`, `description`, `sites`, `url, `timestamp`, `summary`) VALUES
(100, 'Tokotoukan', 'logo-tokotoukan.gif', '<p>\r\n !</p>\r\n', '<p>\r\n <font face=\"arial\" size=\"2\">Τo TOKOTOUKAN </font></p>\r\n', 1, 'http://www.com', ''2017-07-07 17:39:59', '15,00%');
INSERT INTO `eshop_cat` (`eshop_id`, `category_name`, `Parent_category`) VALUES
(100, 'fashion', 'fashion');

How to retrieve Data from both the tables

This is my Database structure for two tables
CREATE TABLE `futstkrprices` (
`name` varchar(50) DEFAULT NULL,
`expiry_date` varchar(25) DEFAULT NULL,
`contract_type` varchar(50) DEFAULT NULL,
`close_price` decimal(15,2) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE `historical_data` (
`symbol_name` varchar(70) DEFAULT NULL,
`open_val` decimal(15,2) DEFAULT NULL,
`high_val` decimal(15,2) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO futstkrprices (name,expiry_date,contract_type,close_price)
values ('ABIRLANUVO' ,'26-MAY-2016','FUTSTK',870.65);
INSERT INTO futstkrprices (name,expiry_date,contract_type,close_price)
values ('ABIRLANUVO' ,'28-APR-2016','FUTSTK',866.40);
INSERT INTO futstkrprices (name,expiry_date,contract_type,close_price)
values ('ABIRLANUVO' ,'30-JUN-2016','FUTSTK',875.95);
INSERT INTO historical_data (symbol_name,open_val,high_val) values ('ABIRLANUVO',872.00,878.25)
Here is the sample Fiddle
http://sqlfiddle.com/#!9/1d4f20
Could you please tell me how can i retrieve data from both the tables
I have tried it as , but its not working
select futstkrprices.name , futstkrprices.expiry_date , futstkrprices.close_price , historical_data.symbol_name ,
historical_data.open_val , historical_data.high_val from futstkrprices LEFT JOIN futstkrprices
ON futstkrprices.name=historical_data.symbol_name;
The desired output i am expecting is
name expiry_date close_price symbol_name open_val high_val
ABIRLANUVO 26-MAY-2016 870.65 ABIRLANUVO 872 878.25
ABIRLANUVO 28-APR-2016 866.4 ABIRLANUVO 872 878.25
ABIRLANUVO 30-JUN-2016 875.95 ABIRLANUVO 872 878.25
Yuou have repetead two times the same table from futstkrprices LEFT JOIN futstkrprices
try this
select
futstkrprices.name ,
futstkrprices.expiry_date ,
futstkrprices.close_price ,
historical_data.symbol_name ,
historical_data.open_val ,
historical_data.high_val
from futstkrprices
LEFT JOIN historical_data
ON futstkrprices.name=historical_data.symbol_name;

MySQL Sub Query takes long time to respond

I've created 3 tables imei, post and view. I've some 1000 records in all the 3 tables. Now when I execute the b/m query, it tooks very long to respond.
Table design & sample data are given below:
CREATE TABLE IF NOT EXISTS `imei` (
`imei_id` int(5) NOT NULL AUTO_INCREMENT,
`imei_no` varchar(30) NOT NULL,
`imei_net` varchar(30) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`imei_id`),
UNIQUE KEY `imei_no` (`imei_no`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1346 ;
CREATE TABLE IF NOT EXISTS `post` (
`post_id` int(5) NOT NULL AUTO_INCREMENT,
`post_title` varchar(60) NOT NULL,
`post_desc` varchar(500) NOT NULL,
`post_author` varchar(30) NOT NULL DEFAULT 'Admin',
`user_id` int(10) NOT NULL DEFAULT '1',
`date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=876 ;
CREATE TABLE IF NOT EXISTS `view` (
`view_id` int(5) NOT NULL AUTO_INCREMENT,
`post_id` int(11) NOT NULL,
`imei_id` varchar(30) NOT NULL,
`status` varchar(10) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`view_id`),
UNIQUE KEY `imei_id` (`imei_id`,`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13706 ;
Values Inside table:
IMEI:
INSERT INTO `imei` (`imei_id`, `imei_no`, `imei_net`, `date`) VALUES
(1, '123456789012345', 'Airtel', '2015-08-06 07:39:47'),
(2, '234567890123456', 'Aircel', '2015-08-06 06:08:33')
POST:
INSERT INTO `post` (`post_id`, `post_title`, `post_desc`, `post_author`, `user_id`, `date`) VALUES
(1, 'NSC Rate Down', 'NSC rates are getting down from today', 'Admin', 1, '2015-07-08 05:29:54'),
(2, 'NCDEX offers cashback', 'NCDEX offers cashback for the previous users', 'Admin', 1, '2015-07-08 05:30:01')
VIEW:
INSERT INTO `view` (`view_id`, `post_id`, `imei_id`, `status`, `date`) VALUES
(1, 1, '1', '1', '2015-08-08 05:04:38'),
(7, 2, '1', '1', '2015-08-08 07:55:25')
Query to Execute:
SELECT
*
FROM
(
SELECT
i.imei_id,
i.imei_no,
p.post_id,
p.post_title,
p.post_desc,
p.date,
1 AS STATUS
FROM
imei i,
post p,
VIEW v
WHERE
i.imei_id = v.imei_id
AND p.post_id = v.post_id
AND i.imei_no = 356554064098771
UNION
SELECT
i.imei_id,
i.imei_no,
p.post_id,
p.post_title,
p.post_desc,
p.date,
0 AS STATUS
FROM
imei i,
post p
WHERE
i.imei_no = 356554064098771
AND p.post_id NOT IN (
SELECT
v.post_id
FROM
imei i,
post p,
VIEW v
WHERE
p.post_id = v.post_id
AND v.imei_id = (
SELECT
i.imei_id
FROM
imei i
WHERE
imei_no = 356554064098771
)
)
) AS temp
WHERE
date >= DATE_SUB(
(
SELECT
date
FROM
imei
WHERE
imei_no = 356554064098771
),
INTERVAL 1 WEEK
)
ORDER BY
date DESC
try this query SELECT post_id,post_title,post_desc,date,if((post_id in (SELECT post_id FROM view WHERE imei_id = (SELECT imei_id FROM imei WHERE imei_no=865645026396909))),1,0) as status FROM post

How to calculate age in query?

How to calculate the age of the user inside a SQL query. Be aware I splitted the database into the fields: birthday, birthmonth and birthyear.
I created a fiddle to show what I mean.
CREATE TABLE IF NOT EXISTS `user_profile` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_birthday` tinyint(4) NOT NULL,
`user_birthmonth` tinyint(4) NOT NULL,
`user_birthyear` smallint(6) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
INSERT INTO `user_profile`
(user_birthday, user_birthmonth, user_birthyear) VALUES (31, 12, 1990)
SqlFiddleDemo
SELECT YEAR(NOW()) - YEAR(birthday) - (DATE_FORMAT(birthday, '%m%d') < DATE_FORMAT(NOW(), '%m%d')) AS Age
FROM (
SELECT
CAST(CONCAT(`user_birthyear`, '-', `user_birthmonth`, '-', `user_birthday`) AS DATE) AS birthday
FROM user_profile ) AS s
Year(getdate()) - birthyear shall be enough