Trying to concatenate three different rows in mysql - mysql

So, I have an attributes table and I'm trying to build a query to concatenate into one column
attributes
------------
id, c_id, key, value
1, 1, 'day', 11
2, 1, 'month', 09
3, 1, 'year', 1999
4, 2, 'day', 14
5, 2, 'month', 11
6, 2, 'year', 2004
And this is the query I wrote,
SELECT
consumer_id,
CONCAT(
(SELECT `value` FROM consumer_attributes WHERE `key` = 'select_day'),
'_',
CONCAT(
(SELECT `value` FROM consumer_attributes WHERE `key` = 'select_month'),
'_',
CONCAT(
(SELECT `value` FROM consumer_attributes WHERE `key` = 'select_year'),
'',
''
)
)
) AS dob
FROM consumer_attributes
It throws out
ERROR CODE: 1242 Subquery returns more than 1 row
Can someone help me out?
output I'm trying to achieve
consumer_id, concat
1, 11_09_1999
2, 14_11_2004

SELECT c_id, CONCAT_WS('_',
(SELECT value FROM consumer_attributes a WHERE `key`='day' AND a.c_id = c.c_id),
(SELECT value FROM consumer_attributes a WHERE `key`='month' AND a.c_id = c.c_id),
(SELECT value FROM consumer_attributes a WHERE `key`='year' AND a.c_id = c.c_id)) AS dob
FROM (SELECT DISTINCT c_id FROM consumer_attributes) c;
https://www.db-fiddle.com/f/pB6b5xrgPKCivFWcpQHsyE/14

Try this,
SELECT `c_id`, CONCAT(GROUP_CONCAT(IF(`key` = 'day', `value`, NULL)),'_',GROUP_CONCAT(IF(`key` = 'month', `value`, NULL)),'_',GROUP_CONCAT(IF(`key` = 'year', `value`, NULL))) as dob
FROM `consumer_attributes`
GROUP BY `c_id`

Note: is it select_day or day ? You should change it above query if its different .
You didnt join subqueries with main query with id columns, so it finds more than one rows for each record . It should be ok if the rest is ok :
SELECT
dmy.consumer_id,
concat (
max(ifnull( (SELECT `value` FROM consumer_attributes dd WHERE `key` = 'day' and dd.id = dmy.id) , -1)) ,'_' ,
max(ifnull( (SELECT `value` FROM consumer_attributes mm WHERE `key` = 'month' and mm.id = dmy.id) , -1) ), '_' ,
max(ifnull( (SELECT `value` FROM consumer_attributes yy WHERE `key` = 'year' and yy.id = dmy.id) , -1)) )
FROM consumer_attributes dmy
group by dmy.consumer_id

Another approach (if you have a lot of data you might want to time different answers);
SELECT c_id, CONCAT(d.d, '_', m.m, '_', y.y) dob
FROM (select c_id, value d FROM consumer_attributes WHERE `key`='day') d
NATURAL JOIN (select c_id, value m FROM consumer_attributes WHERE `key`='month') m
NATURAL JOIN (select c_id, value y FROM consumer_attributes WHERE `key`='year') y;

Related

How to select a primary key which has exact foreign keys matches a given list of values?

For example:
pk_ref fk
====== ===
1 a
1 b
1 c
2 a
2 b
2 d
How do I do a query like the "pseudo" query:
select distinc pk_ref
where fk in all('a', 'c');
The return query result must match all given values for the foreign key in the list.
The result should be:
1
While the following select must not return any records.
select distinc pk_ref
where fk in all('a', 'c', 'd');
How do I do that?
Try this
select pk_ref
from yourtable
group by pk_ref
having count(case when fk = 'a', then 1 end) >= 1
and count(case when fk = 'c' then 1 end) >= 1
To do it dynamically. (considering you are using SQL SERVER)
Create a split string function and pass the input as comma separated values
Declare #input varchar(8000)= 'a,c',#cnt int
set #cnt = len(#input)-len(replace(#input,',','')) + 1
select pk_ref
from yourtable
Where fk in (select split_values from udf_splitstring(#input , ','))
group by pk_ref
having count(Distinct fk) >= #cnt
You can create a split string function from the below link
https://sqlperformance.com/2012/07/t-sql-queries/split-strings
:list is the input list (bind variable). The difference of length() return values is the number of commas in the bind variable. This query, or something very close to it, should work in pretty much any DB product. Tested in Oracle.
select pk_ref
from tbl -- enter your table name here
where ',' || :list || ',' like '%,' || fk || ',%'
group by pk_ref
having count(distinct fk) = 1 + length(:list) - length(replace(:list, ',', ''))
If you can pass the IN operator values as Set, then you can do this as below
Schema:
SELECT * INTO #TAB FROM (
SELECT 1 ID, 'a' FK
UNION ALL
SELECT 1, 'b'
UNION ALL
SELECT 1, 'c'
UNION ALL
SELECT 2, 'a'
UNION ALL
SELECT 2, 'b'
UNION ALL
SELECT 2, 'd'
UNION ALL
SELECT 1, 'a'
)AS A
Used CTE to make 'a','c' as Set
;WITH CTE AS (
SELECT 'a' FK --Here 'a','c' passed as a Set through CTE
UNION
SELECT 'c'
)
,FINAL AS(
SELECT DENSE_RANK() OVER (PARTITION BY ID ORDER BY (FK))AS COUNT_ID, ID, FK
FROM #TAB where FK IN (select FK FROM CTE)
)
SELECT ID FROM FINAL WHERE COUNT_ID>=(SELECT COUNT( FK) FROM CTE)
Select pk_ref where fk='a' and pk_ref in (select pk_ref where fk='c' from yourtable) from yourtable;
or
select pk_ref where fk='a' from yourtable intersect select pk_ref where fk='c' from yourtable;
DECLARE #inputVariable VARCHAR(200) = 'a,b,c,d'
DECLARE #inputValue INT
DECLARE #tblInput TABLE
(
FK VARCHAR(100)
)
INSERT INTO #tblInput
SELECT SUBSTRING( #inputVariable+',',RN,1)
FROM (SELECT TOP 100 ROW_NUMBER() OVER(ORDER BY s.object_id) RN
FROM sys.objects s) s
where LEN(#inputVariable) >= RN
AND SUBSTRING(','+ #inputVariable,RN,1) = ','
SELECT #inputValue = COUNT(1) FROm #tblInput
--#inputVariable
DECLARE #tbl TABLE
(
ID INT,
FK VARCHAR(100)
)
INSERT INTO #tbl
SELECT 1 ID, 'a' FK
UNION ALL
SELECT 1, 'b'
UNION ALL
SELECT 1, 'c'
UNION ALL
SELECT 2, 'a'
UNION ALL
SELECT 2, 'b'
UNION ALL
SELECT 2, 'd'
UNION ALL
SELECT 1, 'a'
SELECT t.ID ,COUNT(DISTINCT t.FK)
FROM #tbl t
INNER JOIn #tblInput ti
ON t.FK = ti.FK
GROUP BY ID
HAVING COUNT(DISTINCT t.FK) = #inputValue

MySQL Stored Procedure Column Name Join Syntax

I'm getting all kinds of errors with this stored procedure, from undefined column names to ambiguous field names.
What I'm trying to do is select each subscriber ID where action, share, test, viral, and total are at the highest value. The subscriberID can will be different for each highest value, so you might be returning up to 5 subscriberIDs. Maybe my logic is off here, but below is my code(Please note this is just for the 'action' column):
SELECT `set1.subscriber_id`, `set1.action`, `set1.share`, `set1.test`, `set1.viral`, ( `set1.action` + `set1.share` + `set1.test` + `set1.viral` ) AS "total", `abuse_flag`
FROM `subscribers_points` set1
JOIN
(
SELECT `subscriber_id`, MAX(`action`) AS actionMax
FROM `subscribers_points`
WHERE `year` = _year
AND `month` = _month
GROUP BY `subscriber_id`
) groupedAction
ON set1.subscriber_id=groupedAction.subscriber_id
WHERE `year` = _year
AND `month` = _month;
^ This resulted in 'Unknown column 'set1.subscriber_id' in 'field list'
This looks correct to me. I don't know what's causing the error.
try this ... without most of the backticks ... you only need the backticks to escape reserved words, etc.
SELECT set1.subscriber_id, set1.action, set1.share, set1.test, set1.viral,
( set1.action + set1.share + set1.test + set1.viral ) AS "total", abuse_flag
FROM subscribers_points set1
JOIN (
SELECT subscriber_id, MAX(`action`) AS actionMax
FROM subscribers_points
WHERE year = _year
AND month = _month
GROUP BY subscriber_id
) as groupedAction
ON set1.subscriber_id=groupedAction.subscriber_id
WHERE year = _year
AND month = _month;
Use 'as' before groupedAction.
SELECT `set1.subscriber_id`, `set1.action`, `set1.share`, `set1.test`, `set1.viral`, ( `set1.action` + `set1.share` + `set1.test` + `set1.viral` ) AS "total", `abuse_flag`
FROM `subscribers_points` set1
JOIN
(
SELECT `subscriber_id`, MAX(`action`) AS actionMax
FROM `subscribers_points`
WHERE `year` = _year
AND `month` = _month
GROUP BY `subscriber_id`
) as groupedAction
ON set1.subscriber_id=groupedAction.subscriber_id
WHERE `year` = _year
AND `month` = _month;

Split values then resolve the values to a name

I need to be able to do something with my column (below) that can contain multiple values. The 'HearAboutEvent' column has multiple values separated by a comma. Each one of these values corresponds to an entry in another table. So the value of 11273 will equal facebook, 11274 will mean radio, and 11275 will mean commercial.
The data I am working with looks like this:
weather ID MemberID SubscriptionID DateEntered ParticipatedBefore ParticipatedBeforeCities WeatherDependent NonRefundable TShirtSize HearAboutEvent
Yes 24 18 1 2013-12-19 0 NULL 10950 10952 10957 11273, 11274, 11275
I am able to do the proper join to resolve the value of 'weather', note it is the first column and the 8th column.
This is the query I have created so far to resolve the values of WeatherDependent:
SELECT CFS1.Name as 'weather', *
FROM FSM_CustomForm_693 t
LEFT JOIN FSM_CustomFormSelectOptions CFS1 ON CFS1.ID = t.WeatherDependent
where t.ID = 24
Ultimately I need to have the data look like this:
weather ID MemberID SubscriptionID DateEntered ParticipatedBefore ParticipatedBeforeCities WeatherDependent NonRefundable TShirtSize HearAboutEvent
Yes 24 18 1 2013-12-19 0 NULL 10950 10952 10957 Facebook, radio, commercial
Things I think you could use to accomplish this are:
A Split TVF FUNCTION - http://msdn.microsoft.com/en-us/library/ms186755.aspx
CROSS APPLY - http://technet.microsoft.com/en-us/library/ms175156.aspx
STUFF & FOR XML PATH - http://msdn.microsoft.com/en-us/library/ms188043.aspx & http://msdn.microsoft.com/en-us/library/ms190922.aspx
Going one step further, you need something like this:
Excuse my profuse use of sub queries.
CREATE FUNCTION dbo.Split (#sep char(1), #s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(#sep, #s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(#sep, #s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(#s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
GO
SELECT
O.A,O.B,O.C,O.D,O.E,O.F,O.G,O.H,O.I,O.J,O.Stuffed
FROM (
SELECT
*
,STUFF((
SELECT ', ' + Name
FROM (
SELECT
V.*
,Y.Name
FROM (
SELECT
'Yes' AS A
,24 AS B
,18 AS C
,1 AS D
,'2013-12-19' AS E
,0 AS F
,NULL AS G
,10950 AS H
,10952 AS I
,10957 AS J
,'11273, 11274, 11275' AS K
)
AS V
CROSS APPLY dbo.Split(',',REPLACE(K,' ','')) AS P
JOIN (
SELECT 11273 AS Id , 'Facebook' AS Name UNION ALL
SELECT 11274 AS Id , 'radio' AS Name UNION ALL
SELECT 11275 AS Id , 'commercial' AS Name
)Y ON y.Id = p.s) ExampleTable
FOR XML PATH('')
), 1, 1, '' )
AS [Stuffed]
FROM (
SELECT
V.*
FROM (
SELECT
'Yes' AS A
,24 AS B
,18 AS C
,1 AS D
,'2013-12-19' AS E
,0 AS F
,NULL AS G
,10950 AS H
,10952 AS I
,10957 AS J
,'11273, 11274, 11275' AS K
)
AS V
CROSS APPLY dbo.Split(',',REPLACE(K,' ','')) AS P
JOIN (
SELECT 11273 AS Id , 'Facebook' AS Name UNION ALL
SELECT 11274 AS Id , 'radio' AS Name UNION ALL
SELECT 11275 AS Id , 'commercial' AS Name
)Y ON y.Id = p.s
)Z
) O
GROUP BY O.A,O.B,O.C,O.D,O.E,O.F,O.G,O.H,O.I,O.J,O.K,O.Stuffed

Concatenation using a mysql variable

The problem in my query particularly in this piece:
#a:= concat(#a, ',', B.call_account_id) AS paid_account_id
Here is the whole query:
SELECT operator_id, paid_account_ids, SUM( goods_count * price ) AS sales_volume, count(*) AS sales_cnt
FROM (
SELECT B.operator_id, #a:= concat(#a, ',', B.call_account_id) AS paid_account_ids, B.call_time, A.goods_count, A.price, UNIX_TIMESTAMP( A.completion_date ) AS paid_ts
FROM call_module_data B
INNER JOIN ak_accounts A ON ( A.account_id = B.call_account_id AND A.goods_count >=1 )
WHERE B.call_status IN (1,7) AND A.status_id = 5
AND operator_id IN ( $op_ids )
$and_str_accounts
GROUP BY A.account_id
HAVING call_time < (paid_ts + $time_shift)
) AS T
GROUP BY operator_id";
So the expression mentioned above should produce the concatenated string of account ids (e.g 3341,4355,4433...). But I got NULL instead of desired string.
Please help to resolve. Thanks in advance.
Use GROUP_CONCAT() function instead of String concatenation
Change
#a:= concat(#a, ',', B.call_account_id) AS paid_account_id
above string to
GROUP_CONCAT(B.call_account_id) AS paid_account_ids
Final Answer:
SELECT operator_id, GROUP_CONCAT(paid_account_ids) AS paid_account_ids,
SUM(goods_count * price) AS sales_volume, COUNT(*) AS sales_cnt
FROM (SELECT B.operator_id, GROUP_CONCAT(B.call_account_id) AS paid_account_ids,
B.call_time, A.goods_count, A.price,
UNIX_TIMESTAMP(A.completion_date) AS paid_ts
FROM call_module_data B
INNER JOIN ak_accounts A ON A.account_id = B.call_account_id AND A.goods_count >=1
WHERE B.call_status IN (1,7) AND A.status_id = 5 AND operator_id IN ($op_ids)
$and_str_accounts
GROUP BY A.account_id HAVING call_time < (paid_ts + $time_shift)
) AS T
GROUP BY operator_id;

Order By Issue with MySQL vs SQL Server

I have one SQL query in SQL Server like this
SELECT
CASE WHEN ROW_NUMBER() OVER(PARTITION BY _no ORDER BY _no asc) = 1 THEN
_no ELSE '' END
as row_no,
_no,
_name,
r._names
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
ORDER BY _no
Output:
row_no _no _name _names
------ ---- --------------- ------
1 1 kratika One
1 kratika kastwar One
1 vikas One
2 2 vikas two
And the same I am doing in MySQL like this
SELECT
CASE WHEN _no = #i THEN '' ELSE #i := _no END
as row_no,
_no,
_name,
r._names
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
,
(SELECT #i := '') temp
ORDER BY _no
Output :
1 1 vikas One
1 kratika One
1 1 kratika kastwar One
2 2 vikas two
But I am expecting output in MySQL like this
1 1 kratika One
1 kratika kastwar One
1 vikas One
2 2 vikas two
I don't want to use query like this in MySQL as desc here MYSQL Order By W/Count
SELECT
CASE WHEN _no = #i THEN '' ELSE #i := _no END
as row_no,
_no,
_name,
_names
FROM
(SELECT
*
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
,
(SELECT #i := '') temp
ORDER BY _no) t
How I can achieve the same in MySQL, query performance is major parameter
I think what's happening here is that MySQL is constructing the resultset and then going through an extra step to order it according to the ORDER BY clause. Since the 'kratika kastwar' row comes after the row where _no is 2, you get the unexpected output.
The solution, I guess, would be to put the basic SELECT (without the special user-variable shenanigans) in a subquery in the FROM clause, applying the ORDER BY clause to the subquery. Then do the user-variable work in the outer query. That way the ordering has already happened.
Edit: I see that you said you don't want to do this. I don't think you have a choice, unless you can find a way to get MySQL to not do the ORDER BY by performing a filesort step on the computed results (very unlikely).
SELECT
CASE WHEN _no = #i THEN '' ELSE #i := _no END
as row_no,
_no,
_name,
_names
FROM
(SELECT
*
FROM
(
SELECT '1' as _no, 'vikas' as _name UNION ALL
SELECT '1', 'kratika' UNION ALL
SELECT '2', 'vikas' UNION ALL
SELECT '1', 'kratika kastwar'
) t
INNER JOIN
(
SELECT '1' as _nos, 'One' as _names UNION ALL
SELECT '2', 'two'
) r
ON r._nos = t._no
,
(SELECT #i := '')