SQL query for object with specific entries on a join table - sql

I have a join table with the following columns:
target_id
assoc_id
int_attr
They represent my target object, its associated object, and an integer attribute that describes the association.
I am given a hash with keys representing the association attribute and values which contain the associated id with that attribute. For example:
{
1: [3, 5],
2: [7, 9],
}
I am trying to develop an SQL query which finds all target_ids with the appropriate join table entries. In the example above, it would find any target object with the 4 entries:
`targets_assocs`
target_id assoc_id int_attr
X 3 1
X 5 1
X 7 2
X 9 2
A 3 1
A 5 1
A 7 2
A 9 2
C 2 1
C 4 1
C 6 2
C 8 2
In this case, it would return X and A, ignoring, C.
I was trying to use some type of HAVING clause. I am trying to avoid having multiple nested subqueries using IF EXISTS. Any thoughts or advice would be appreciated.

I really have not written requests for MySQL, sorry for typos.
SELECT `target_id` FROM (
SELECT `target_id`, count(*) FROM (
SELECT `targets`.`target_id`, `targets_assocs`.`int_attr` FROM `targets`
INNER JOIN `targets_assocs` ON `targets_assocs`.`target_id` = `targets`.`id`
GROUP BY `targets`.`target_id`, `targets_assocs`.`int_attr`
)
GROUP BY `target_id`
HAVING COUNT(*) = 2)

Related

How to Quickly Flatten a SQL Table

I'm using Presto. If I have a table like:
ID CATEGORY VALUE
1 a ...
1 b
1 c
2 a
2 b
3 b
3 d
3 e
3 f
How would you convert to the below without writing a case statement for each combination?
ID A B C D E F
1
2
3
I've never used Presto and the documentation seems pretty thin, but based on this article it looks like you could do
SELECT
id,
kv['A'] AS A,
kv['B'] AS B,
kv['C'] AS C,
kv['D'] AS D,
kv['E'] AS E,
kv['F'] AS F
FROM (
SELECT id, map_agg(category, value) kv
FROM vtable
GROUP BY id
) t
Although I'd recommend doing this in the display layer if possible since you have to specify the columns. Most reporting tools and UI grids support some sort of dynamic pivoting that will create columns based on the source data.
My 2 cents:
If you know "possible" values:
SELECT
m['web'] AS web,
m['shopping'] AS shopping,
m['news'] AS news,
m['music'] AS music,
m['images'] AS images,
m['videos'] AS videos,
m[''] AS empty
FROM (
SELECT histogram(data_tab) AS m
FROM datahub
WHERE
year = 2017
AND month = 5
AND day = 7
AND name = 'search'
) searches
No PIVOT function (yet)!

SQL Getting multiple rows from a single row

I need to accomplish the following :
I have a table with multiple column (c1, c2, c3, c4 ... cn).
I want a query that would return multiple rows in the following fashion (r1 r2 .. rx are the rows in the original table) :
r1c1 r1c2 r1c3
r1c4 r1c5 r1c6
...
r1cn-2 r1cn-1 r1cn
r2c1 r2c2 r2c3
r2c4 r2c5 r2c6
...
r2cn-2 r2cn-1 r2cn
...
rxc1 rxc2 rxc3
rxc4 rxc5 rxc6
...
rxcn-2 rxn-1 rxcn
I know I can use unions and repeat basically the same query n times, but I need to use that query in a web based reporting system that I have no control over and the query is to big for the maximum number of characters allowed in queries.
Any suggestions ?
Thank you !
EDIT : FYI I'm building a report in a report tool I can't change using a database I can't change. So using custom functions/procedures is not a solution. It has to be a PL-SQL query.
To be more specific, i need to have multiple rows from the original row, lets say row 1 is
a b c d e f h i j
and row 2 is
1 2 3 4 5 6 7 8 9
then I would get the following table with 3 columns :
a b c
d e f
h i j
1 2 3
4 5 6
7 8 9
So number 1, if you have a set number of columns in the original table that is divisible by 3, you can just do that many UNION ALL.
Your only other options are pivot or a pointer, neither of which is going to be any better.
The simple case when n is divisible by 3 just use rownum and union:
WITH T1 AS
(
SELECT rownum as rn,1 as tNum, c1 as s1,c2 as s2,c3 as s3 FROM T
UNION ALL
SELECT rownum as rn,2 as tNum, c4 as s1,c5 as s2,c6 as s3 FROM T
UNION ALL
SELECT rownum as rn,3 as tNum, c7 as s1,c8 as s2,c9 as s3 FROM T
)
SELECT s1,s2,s3 FROM T1
ORDER BY rn,tNum
SQLFiddle demo

Same entity from different tables/procedures

I have 2 procedures (say A and B). They both return data with similar columns set (Id, Name, Count). To be more concrete, procedures results examples are listed below:
A:
Id Name Count
1 A 10
2 B 11
B:
Id Name Count
1 E 14
2 F 15
3 G 16
4 H 17
The IDs are generated as ROW_NUMBER() as I don't have own identifiers for these records because they are aggregated values.
In code I query over the both results using the same class NameAndCountView.
And finally my problem. When I look into results after executing both procedures sequentially I get the following:
A:
Id Name Count
1 A 10 ->|
2 B 11 ->|
|
B: |
Id Name Count |
1 A 10 <-|
2 B 11 <-|
3 G 16
4 H 17
As you can see results in the second set are replaced with results with the same IDs from the first. Of course the problem take place because I use the same class for retrieving data, right?
The question is how to make this work without creating additional NameAndCountView2-like class?
If possible, and if you don't really mind about the original Id values, maybe you can try having the first query return even Ids :
ROW_NUMBER() over (order by .... )*2
while the second returns odd Ids :
ROW_NUMBER() over (order by .... )*2+1
This would also allow you to know where the Ids come from.
I guess this would be repeatable with N queries by having the query number i selecting
ROW_NUMBER() over (order by .... )*n+i
Hope this will help

Finding contiguous regions in a sorted MS Access query

I am a long time fan of Stack Overflow but I've come across a problem that I haven't found addressed yet and need some expert help.
I have a query that is sorted chronologically with a date-time compound key (unique, never deleted) and several pieces of data. What I want to know is if there is a way to find the start (or end) of a region where a value changes? I.E.
DateTime someVal1 someVal2 someVal3 target
1 3 4 A
1 2 4 A
1 3 4 A
1 2 4 B
1 2 5 B
1 2 5 A
and my query returns rows 1, 4 and 6. It finds the change in col 5 from A to B and then from B back to A? I have tried the find duplicates method and using min and max in the totals property however it gives me the first and last overall instead of the local max and min? Any similar problems?
I didn't see any purpose for the someVal1, someVal2, and someVal3 fields, so I left them out. I used an autonumber as the primary key instead of your date/time field; but this approach should also work with your date/time primary key. This is the data in my version of your table.
pkey_field target
1 A
2 A
3 A
4 B
5 B
6 A
I used a correlated subquery to find the previous pkey_field value for each row.
SELECT
m.pkey_field,
m.target,
(SELECT Max(pkey_field)
FROM YourTable
WHERE pkey_field < m.pkey_field)
AS prev_pkey_field
FROM YourTable AS m;
Then put that in a subquery which I joined to another copy of the base table.
SELECT
sub.pkey_field,
sub.target,
sub.prev_pkey_field,
prev.target AS prev_target
FROM
(SELECT
m.pkey_field,
m.target,
(SELECT Max(pkey_field)
FROM YourTable
WHERE pkey_field < m.pkey_field)
AS prev_pkey_field
FROM YourTable AS m) AS sub
LEFT JOIN YourTable AS prev
ON sub.prev_pkey_field = prev.pkey_field
WHERE
sub.prev_pkey_field Is Null
OR prev.target <> sub.target;
This is the output from that final query.
pkey_field target prev_pkey_field prev_target
1 A
4 B 3 A
6 A 5 B
Here is a first attempt,
SELECT t1.Row, t1.target
FROM t1 WHERE (((t1.target)<>NZ((SELECT TOP 1 t2.target FROM t1 AS t2 WHERE t2.DateTimeId<t1.DateTimeId ORDER BY t2.DateTimeId DESC),"X")));

Why does this query return "incorrect" results?

I have 3 tables:
'CouponType' table:
AutoID Code Name
1 CouT001 SunCoupon
2 CouT002 GdFriCoupon
3 CouT003 1for1Coupon
'CouponIssued' table:
AutoID CouponNo CouponType_AutoID
1 Co001 1
2 Co002 1
3 Co003 1
4 Co004 2
5 Co005 2
6 Co006 2
'CouponUsed' table:
AutoID Coupon_AutoID
1 2
2 3
3 5
I am trying to join 3 tables together using this query below but apparently I am not getting right values for CouponIssued column:
select CouponType.AutoID, Code, Name, Count(CouponIssued.CouponType_AutoID), count(CouponUsed.Coupon_AutoID)
from (CouponType left join CouponIssued
on (CouponType.AutoID = CouponIssued.CouponType_AutoID))
left join CouponUsed
on (couponUsed.Coupon_AutoID = CouponIssued.AutoID)
group by CouponType.AutoID, code, name
order by code
The expected result should be like:
**Auto ID Code Name Issued used**
1 CouT001 SunCoupon 3 2
2 CouT002 GdFriCoupon 3 1
3 CouT003 1for1Coupon 0 0
Thanks!
SELECT t.AutoID
,t.Code
,t.Name
,count(i.CouponType_AutoID) AS issued
,count(u.Coupon_AutoID) AS used
FROM CouponType t
LEFT JOIN CouponIssued i ON i.CouponType_AutoID = t.AutoID
LEFT JOIN CouponUsed u ON u.Coupon_AutoID = i.AutoID
GROUP BY 1,2,3;
You might consider using less confusing names for your table columns. I have made very good experiences with using the same name for the same data across tables (as far as sensible).
In your example, AutoID is used for three different columns, two of which appear a second time in another table under a different name. This would still make sense if Coupon_AutoID was named CouponIssued_AutoID instead.
change count(Coupon.CouponType_AutoID) to count(CouponIssued.CouponType_AutoID) and count(Coupon.Coupon_AutoID) to count(CouponUsed.Coupon_AutoID)