How to get queries by a user group - sql

I'd like to get all queries run by users in a specific user group for a Redshift database. Here's the query I'm running:
select
q.*,
u.usename,
swq.total_queue_time / 1000000 as queue_time
from stl_query q
inner join pg_user u on q.userid = u.usesysid
inner join pg_group g on u.usesysid = ANY (g.grolist)
inner join stl_wlm_query swq on q.query = swq.query
where q.userid <> 1
AND database = 'mydb'
AND g.groname = 'ops'
order by q.starttime desc;
However, I'm getting Column "g.grolist" has unsupported type "integer[]". I've tried other forms of the same query (e.g., putting the ANY condition in WHERE), but I keep getting the same error. How can I check whether a user ID occurs in the list of user IDs in pg_group?

I found this redshift guide having array types included in the unsupported list of PostgresSQL data types, and that's causing your SQL error of column has unsupported type.
Redshift is not exactly Postgres & thus doesn't have full feature support for all Postgres data types and functions. So refering redshift guide for any errors/differences in behaviour you encounter will be the best bet.
Find out more differences here: Amazon Redshift and PostgreSQL
For unsupported data types, it states:
If a query attempts to use an unsupported data type, including explicit or implicit casts, it will return an error.
However redshift does support some array & json-array function(s) which you can use to play with array column type. Like below query will output your desired result using array_to_string.
select
q.*,
u.usename,
swq.total_queue_time / 1000000 as queue_time
from stl_query q
inner join pg_user u on q.userid = u.usesysid
inner join pg_group g on array_to_string(g.grolist,',') like '%' || u.usesysid || '%'
inner join stl_wlm_query swq on q.query = swq.query
where q.userid <> 1
AND database = 'mydb'
AND g.groname = 'ops'
order by q.starttime desc;

Related

MS Access INNER JOIN/LEFT JOIN problems

I have the following SQL string which tries to combine an INNER JOIN with a LEFT JOIN in the FROM section.
As you can see I use table VIP_APP_VIP_SCENARIO_DETAIL_LE to perform the query. When I use it against this table, Access give me an "Invalid Operation" error.
Interestingly, when I use the EXACT same query using the VIP_APP_VIP_SCENARIO_DETAIL_BUDGET or VIP_APP_VIP_SCENARIO_DETAIL_ACTUALS table, it performs flawlessly.
So why would it work on two tables but not the other? All fields are in all tables and the data types are correct.
As a side note: on the query with the error, if I change the LEFT JOIN to an INNER JOIN, it runs with no problem! I really need a LEFT JOIN though.
SELECT
D.MATERIAL_NUMBER,
D.MATERIAL_DESCRIPTION,
D.PRODUCTION_LOT_SIZE,
D.STANDARDS_NAME,
D.WORK_CENTER,
S.OP_SHORT_TEXT,
S.OPERATION_CODE,
D.LINE_SPEED_UPM,
D.PERCENT_STD,
D.EQUIPMENT_SU,
D.EQUIPMENT_CU,
D.OPERATOR_NUM,
V.COSTING_LOT_SIZE,
V.VOL_TOTAL_ADJ
FROM
([STDS_SCENARIO: TEST] AS D INNER JOIN MASTER_SUMMARY AS S ON
D.MATERIAL_NUMBER = S.MATERIAL_NUMBER AND D.WORK_CENTER = S.WORK_CENTER)
LEFT JOIN
(SELECT ITEM_CODE, COSTING_LOT_SIZE, VOL_TOTAL_ADJ
FROM
VIP_APP_VIP_SCENARIO_DETAIL_LE
WHERE SCENARIO_ID = 16968) AS V ON D.MATERIAL_NUMBER = V.ITEM_CODE
ORDER BY D.MATERIAL_NUMBER, D.STANDARDS_NAME, S.OPERATION_CODE;
tried to mock this up in SQL server with some tables of my own, but the structure seemed to work, this follows the pattern referenced above. (hopefully no syntax errors left here)
SELECT * FROM (
select
D.MATERIAL_NUMBER,
D.MATERIAL_DESCRIPTION,
D.PRODUCTION_LOT_SIZE,
D.STANDARDS_NAME,
D.WORK_CENTER,
S.OP_SHORT_TEXT,
S.OPERATION_CODE,
D.LINE_SPEED_UPM,
D.PERCENT_STD,
D.EQUIPMENT_SU,
D.EQUIPMENT_CU,
D.OPERATOR_NUM
FROM [STDS_SCENARIO: TEST] D
INNER JOIN MASTER_SUMMARY S
ON D.MATERIAL_NUMBER = S.MATERIAL_NUMBER AND D.WORK_CENTER = S.WORK_CENTER) AS J
LEFT JOIN
(SELECT ITEM_CODE, COSTING_LOT_SIZE, VOL_TOTAL_ADJ
FROM
VIP_APP_VIP_SCENARIO_DETAIL_LE
WHERE SCENARIO_ID = 16968) AS V ON J.MATERIAL_NUMBER = V.ITEM_CODE
ORDER BY J.MATERIAL_NUMBER, J.STANDARDS_NAME, J.OPERATION_CODE;
Had help from a friend and we discovered that it was a casting problem between a linked Oracle table and the Access table. To fix the problem we casted both sides of the linked fields to a string:
CSTR(D.[MATERIAL_NUMBER]) = CSTR(V.[ITEM_CODE])

SQL Server : multi-join with tuple IN clause

I'm trying to join 4 tables that have a somewhat complex relationship. Because of where this will be used, it needs to be contained in a single query, but I'm having trouble since the primary query and the IN clause query both join 2 tables together and the lookup is on two columns.
The goal is to input a SalesNum and SalesType and have it return the Price
Tables and relationships:
sdShipping
SalesNum[1]
SalesType[2]
Weight[3]
sdSales
SalesNum[1]
SalesType[2]
Zip[4]
spZones
Zip[4]
Zone[5]
spPrices
Zone[5]
Price
Weight[3]
Here's my latest attempt in T-SQL:
SELECT
spp.Price
FROM
spZones AS spz
LEFT OUTER JOIN
spPrices AS spp ON spz.Zone = spp.Zone
WHERE
(spp.Weight, spz.Zip) IN (SELECT ship.Weight, sales.Zip
FROM sdShipping AS ship
LEFT OUTER JOIN sdSales AS sales ON sales.SalesNum = ship.SalesNum
AND sales.SalesType = ship.SalesType
WHERE sales.SalesNum = (?)
AND ship.SalesType = (?));
SQL Server Management Studio says I have an error in my syntax near ',' (appropriately useless error message). Does anybody have any idea whether this is even allowed in Microsoft's version of SQL? Is there perhaps another way to accomplish it? I've seen the multi-key IN questions answered on here, but never in the case where both sides require a JOIN.
Many databases do support IN on tuples. SQL Server is not one of them.
Use EXISTS instead:
SELECT spp.Price
FROM spZones spz LEFT OUTER JOIN
spPrices spp
ON spz.Zone = spp.Zone
WHERE EXISTS (SELECT 1
FROM sdShipping ship LEFT JOIN
sdSales sales
ON sales.SalesNum = ship.SalesNum AND
sales.SalesType = ship.SalesType
WHERE spp.Weight = ship.Weight AND spz.Zip = sales.Zip AND
sales.SalesNum = (?) AND
ship.SalesType = (?)
);

Convert a complex PostgreSQL query to Ruby

I'm new here and have some difficult to convert a complex Postgres query to Ruby. Here is the query:
SELECT date_part('year', p.created_at) AS anio,
date_part('month'::text, p.created_at) AS mes,
p.id_pais, pa.nombre AS nombre_pais,
pr.id_region, re.nombre AS nombre_region,
co.id_provincia, pr.nombre AS nombre_provincia,
p.id_comuna, co.nombre AS nombre_comuna,
p.id_tipo_propiedad, p.id_modalidad,
count(*) AS total_propiedades,
sum((p.precio/mo.conversion_dolar)/p.dimension_propiedad) AS suma_precio_m2_dolar,
sum((p.precio/mo.conversion_dolar)/p.dimension_propiedad)/count(*) AS promedio_precio_m2_dolar
FROM propiedad AS p
INNER JOIN monedas AS mo ON (p.id_moneda = mo.id)
INNER JOIN comuna AS co ON (p.id_comuna = co.id)
INNER JOIN provincia AS pr ON (co.id_provincia = pr.id)
INNER JOIN region AS re ON (pr.id_region = re.id)
INNER JOIN pais AS pa ON (p.id_pais = pa.id)
WHERE p.id_modalidad IS NOT NULL
AND p.created_at IS NOT NULL
AND p.precio > 1
AND p.dimension_propiedad > 1
GROUP BY date_part('year',p.created_at), date_part('month'::text, p.created_at), p.id_tipo_propiedad,
p.id_modalidad, p.id_pais, pr.id_region, co.id_provincia, p.id_comuna, pa.nombre, re.nombre, pr.nombre, co.nombre
If you can help me with this i'll appreciate it.
I'd just leave something like that as plain SQL and hand it to select_rows:
connection.select_rows(%q{
-- your big pile of SQL goes here
}).each do |row|
# row will be an array of Strings in here
end
You'll have to unstringify things yourself but that shouldn't be terribly difficult. You could also use execute:
rows = connection.execute(%q{
-- SQL goes here...
})
rows.each do |row|
# row will be a hash
end
Your query is pulling a bunch of data out of the database that doesn't correspond to any particular model so there's not much point in trying to get ActiveRecord to produce that SQL. If the query was producing a model, then you'd use Model.find_by_sql (and still avoid trying to convince ActiveRecord to produce the SQL you're after).

sql joining as alias does not working

i am new to sql joins.. i have project that is 5 year old . Now i have to deploy it some new server .so deploy it to other server there i am facing some sql problem. here is the qyery .
SELECT DISTINCT d.*,DATE_FORMAT(d.downloads_updated, '%c/%d/%Y') AS updated,DATE_FORMAT(d.downloads_created, '%c/%d/%Y') AS created, s2.strings_english as title, s2.strings_english as description
FROM strings s, downloads d,
products_has_downloads pd
inner JOIN strings s2 ON d.downloads_description = s.strings_id WHERE d.downloads_id = pd.downloads_id AND s.strings_id = d.downloads_title AND d.downloads_status = 'Live' AND d.downloads_level = 'Public'
ORDER BY d.downloads_updated DESC LIMIT 5
i am getting this error
1054 - Unknown column 'd.downloads_description' in 'on clause'
i have not written this sql query.it is working fine on old server .
I am new to join and database .please can any one help me .
You are mixing both implicit and explicit join syntax which will not work.
You have the following implicit syntax where the tables are joined by commas:
FROM strings s, downloads d, products_has_downloads pd
The JOIN syntax has a higher precedence to the comma syntax so the alias for downloads is not available in the ON clause.
Try using all of the same syntax. I changed your query to use only explicit JOIN syntax:
SELECT DISTINCT d.*,
DATE_FORMAT(d.downloads_updated, '%c/%d/%Y') AS updated,
DATE_FORMAT(d.downloads_created, '%c/%d/%Y') AS created,
s2.strings_english as title,
s2.strings_english as description
FROM strings s
INNER JOIN downloads d
ON d.downloads_description = s.strings_id
INNER JOIN products_has_downloads pd
on d.downloads_id = pd.downloads_id
inner JOIN strings s2
on s2.strings_id = d.downloads_title
WHERE d.downloads_status = 'Live'
AND d.downloads_level = 'Public'
ORDER BY d.downloads_updated DESC
LIMIT 5

hibernate - HQL joins on many clauses

I've been reading Hibernate documentation, but I haven't found anything that would explain how to do the following.
I have the following SQL code that I'm trying to convert to HQL:
SELECT {msg.*}, {cmd.*}
FROM Schema.Messages AS msg
LEFT OUTER JOIN schema.send_commands AS cmd
ON cmd.message_key = msg.unique_key
AND ( lower(cmd.status) IN (lower('failed') ) )
WHERE msg.sequence_received < 10";
The mainissue I'm having is that I'm unable to have two clauses on a LEFT OUTER JOIN. HQL allows me to have
ON cmd.message_key = msg.unique_key
, but how do I add the
AND clause 2?
You can add extra join conditions using with keyword, something like this (depends on your mapping):
SELECT m, c
FROM Message m LEFT JOIN m.commands c WITH (lower(c.status) = 'failed')
WHERE m.sequenceReceived < 10
See also:
16.3. Associations and joins