The query is meant to return the percentage based on value from one table being divided by the value of another table. However, there is something wrong and I am missing it.
similar problems noted on the board looked related to JOIN, but did not seem to be the problem, when I tried and explicit join -- basically mysql was like -- now you are an idiot-- I must have did that wrong or that is not the problem.
SELECT (pathogenPop / locationpop) as PercentInfected
FROM (
(SELECT apinfectcount.APInfectCountInfected
as pathogenPop, apinfectcount.APInfectCountLocation
FROM apstart.apinfectcount
GROUP BY apinfectcount.APInfectCountLocation) as pathogenPop
Inner JOIN
(SELECT apcountrypop.apcountrypopPopulation
as locationpop, apcountrypop.apcountrypopCountry
FROM apstart.apcountrypop
GROUP BY apcountrypop.apcountrypopCountry)
as locationpop
on apinfectcount.APInfectCountLocation = apcountrypop.apcountrypopCountry
and apinfectcount.APInfectCountWeek = 23);
Table Schema: apcountrypop
idapcountrypop INT(11)
apcountrypopCountry VarChar(45)
apcountrypopPopulation FLOAT
Table Schema: apinfectcount
idAPInfectCount INT(11)
APInfectCountLocation VarChar(45)
APInfectCountOutBreak VarChar(45)
APInfectCountPathogen VarChar(45)
APInfectCountInfected FLOAT
APInfectCountDead FLOAT
APInfectCountWeek VarChar(45)
If it worked --
it would assign apinfectcount.APInfectCountInfected to pathogenPop
and apcountrypop.apcountrypopPopulation to locationpop
for the values where the locations are the same(apinfectcount.APInfectCountLocation = apcountrypop.apcountrypopCountry)
then it would return the value of the apinfectcount table value is divided by the apcountrypop table to give the percentage.
so in this specific example I only have sample data so I am just wanted to return one value so I added the where clause to just test the logic and syntax.
I appreciate the help.
You have assugned the tables alias pathogenPop and locationpop so
you need pathogenPop.APInfectCountLocation = locationpop.apcountrypopCountry
and pathogenPop.APInfectCountWeek = 23 in ON clause
SELECT (pathogenPop / locationpop) as PercentInfected
FROM (
(SELECT apinfectcount.APInfectCountInfected
as pathogenPop, apinfectcount.APInfectCountLocation
FROM apstart.apinfectcount
GROUP BY apinfectcount.APInfectCountLocation) as pathogenPop
Inner JOIN
(SELECT apcountrypop.apcountrypopPopulation
as locationpop, apcountrypop.apcountrypopCountry
FROM apstart.apcountrypop
GROUP BY apcountrypop.apcountrypopCountry)
as locationpop
on pathogenPop.APInfectCountLocation = locationpop.apcountrypopCountry
and pathogenPop.APInfectCountWeek = 23) T;
and also a table alias for the outer FROM(..) T
I don't have the database to test against so I'm not 100% certain this will run, but would the following query not be a bit simpler?
SELECT (apinfectcount.APInfectCountInfected / apcountrypop.apcountrypopPopulation) as PercentInfected, apinfectcount.APInfectCountLocation
FROM apinfectcount
INNER JOIN apcountrypop ON apcountrypop.apcountrypopCountry = apinfectcount.APInfectCountLocation
WHERE apinfectcount.APInfectCountWeek = 23
GROUP BY apinfectcount.APInfectCountLocation
And I assume there is only one location record per location in each table?
There is an issue within a query. As scope of apinfectcount.APInfectCountLocation column and apcountrypop.apcountrypopCountry column is limited to subquery only you cannot use it outside the subquery (within where clause).
You can check out these docs on subquery https://learn.microsoft.com/en-us/sql/relational-databases/performance/subqueries?view=sql-server-2017
Refer code below.
SELECT (countInfected / countrypopulation) as PercentInfected
FROM (
(SELECT apinfectcount.APInfectCountInfected
as countinfected, apinfectcount.APInfectCountLocation, APInfectCountWeek as
countweek
FROM apstart.apinfectcount
GROUP BY apinfectcount.APInfectCountLocation) as pathogenPop
Inner JOIN
(SELECT apcountrypop.apcountrypopPopulation
as countrypopulation, apcountrypop.apcountrypopCountry
FROM apstart.apcountrypop
GROUP BY apcountrypop.apcountrypopCountry)
as locationpop
on pathogenPop.countinfected = locationpop.countrypopulation
and pathogenPop.countweek= 23);
Related
I am having trouble with a new IMDB like system I'm building. My specific issue is that when I run:
CREATE VIEW `directors` AS
SELECT
`stars`.`id` AS `movie_id`,
`stars`.`title`,`stars`.`rating`,
`stars`.`storyline`,
`stars`.`star`,
`people_list`.`name` AS `director`
FROM `stars`
INNER JOIN `stars`
ON `movie_directors`.`movie` = `stars`.`id`
INNER JOIN `people_list`
ON `movie_directors`.`director` = `people_list`.`id`
WHERE `movie_directors`.`enabled` = 1;
I get the following error:
#1052 - Column 'stars.id' in field list is ambiguous
All of the questions I've found on here seem to relate to when you don't prefix the column name with a table name or, in this case, a view name since I'm writing a view to build off another view
You are selecting from stars and then INNER JOINing on stars:
SELECT ... FROM stars INNER JOIN stars
I think that you probably want to join with movie_directors based on your query.
You are using a self join (starts table is used two time) in this case you need an alias for refer the proper table instance
CREATE VIEW `directors` AS
SELECT
`stars`.`id` AS `movie_id`
, `stars`.`title`
,`stars`.`rating`
, `stars`.`storyline`
, `stars`.`star`
, `people_list`.`name` AS `director`
FROM `stars`
INNER JOIN `stars` as s2 ON `movie_directors`.`movie` = s2.`id`
INNER JOIN `people_list` ON `movie_directors`.`director` = `people_list`.`id`
WHERE `movie_directors`.`enabled` = 1;
I think it's because you are not aliasing correctly.
It should be something like
select ...
from stars
inner join stars as anothername
It looks to be ambiguous because you have two references to the stars table. Your FROM clause and your first INNER JOIN.
It looks like you are intending to join on movie_directors instead of INNER JOIN stars clause. E.g.
CREATE VIEW `directors` AS SELECT
`stars`.`id` AS `movie_id`,
`stars`.`title`,`stars`.`rating`, `stars`.`storyline`, `stars`.`star`, `people_list`.`name` AS `director`
FROM `stars`
INNER JOIN `movie_directors` ON `movie_directors`.`movie` = `stars`.`id`
INNER JOIN `people_list` ON `movie_directors`.`director` = `people_list`.`id` WHERE `movie_directors`.`enabled` = 1;
Hope this helps!
I got 2 tables tbl_issued and tbl_transaction.
tbl_issued has its columns, ItemID,Item,Serial,Quantity and Size. While tbl_transaction has its columns Released,Received,Approved and Department
My problem is I want to get their columns in 1 query, this is mysql query
SELECT `ItemID`,`Item`,`Serial`,`Quantity`,`Size`,`Class`,`Unit`,(SELECT `Released` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Released`,
(SELECT `Received` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Received`,
(SELECT `Approved` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Aprroved`,
(SELECT `Department` FROM `tbl_transaction` WHERE `TransactionID` = 12458952) AS `Department`
FROM `tbl_issued` WHERE `TransactionID` = 12458952
but transferring this on vb.net does not provide output.
Any ideas how i will translate this query to vb.net? Thanks in advance for help!
I don't know what you are trying to do but if you want it to be simplified, here's how. Have you tried Inner Joins? It's like this.
SELECT ItemID, Item, Serial, Quantity, Size, Class, Unit, Released, Received,
Approved, Deparment from tbl_issued a INNER JOIN tbl_transaction b on
a.TransactionID = b.TransactionID Where a.TransactionID = 12458952
I assume that both tables have TransactionID based on your query.
I have
TABLE 1: r_profile_token
Columns:
r_sequence int(45) AI PK
r_profileid varchar(45)
r_token varchar(300)
r_deviceType int(1)
r_date date
r_time time
and
TABLE 2: r_token_arn
Columns:
r_token varchar(300) PK
r_arn varchar(300)
I need a result of the form -
r_profileid
r_arn
r_deviceType
where I can specify the r_profileid.
So far my SQL statement is:
SELECT
b.r_arn,
a.r_deviceType
FROM
coffee2.r_profile_token a INNER JOIN
coffee2.r_token_arn b
ON a.r_token=b.r_token;
Which returns r_arn and r_deviceType but for all r_profileid?
How do I modify the statement so that it returns me r_arn and r_deviceType only corresponding to a specific r_profileid?
Use a WHERE clause.
SELECT B.R_ARN, A.R_DEVICETYPE
FROM COFFEE2.R_PROFILE_TOKEN A
INNER JOIN
COFFEE2.R_TOKEN_ARN B
ON A.R_TOKEN=B.R_TOKEN
WHERE R_PROFILEID = 'SOME_VALUE';
If you want for a single profileid, then use
WHERE R_PROFILEID = 'SOME_VALUE';
If you want for a range of profileIds , then use
WHERE R_PROFILE_ID IN ('VALUE1','VALUE2','VALUE3');
You can try this Query against your requirements.
SELECT
b.r_arn,
a.r_deviceType ,
a.r_profileid
FROM
r_profile_token a
INNER JOIN
r_token_arn b
ON
a.r_token=b.r_token
where r_profileid='profile name';
You need to put a where condition in your MYSql query.
select b.r_arn, a.r_deviceType from coffee2.r_profile_token a
INNER JOIN coffee2.r_token_arn b on a.r_token=b.r_token
where r_profileid = "Specific value";
select b.r_arn, a.r_deviceType, a.r_profileid from r_profile_token a
INNER JOIN r_token_arn b on
a.r_token=b.r_token;
I am building an AJAX like search page which allows a customer to select a number filters that will narrow down the search. For instance, a user has selected an 'iPhone 5' and has additional filters for capacity (32GB, 64GB) & colour (black, white..).
The user can only select a single radio box per category (so they could select 32GB & Black).. but they could not select (32GB & 64GB & black as two of these belong to the 'capacity' category).
I have added the schema here on sqlfiddle (please ignore the fact i've removed the primary keys they exist in the proper app they have just been removed along with some other fields/data to minimise the sqlfiddle)
http://sqlfiddle.com/#!2/964425
Can anyone suggest the best way to create the query to do the following:
Get all the prices for device_id '2939' (iPhone 5) which has the 'attributes' of '32GB' AND 'Black'
I currently have this - but this only works when selecting for a single attribute:
// search for device with '64GB' & 'Black' attributes (this currently doesn't return any rows)
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
AND `attribute_option_id` = '19'
AND `attribute_option_id` = '47';
// search for device with '64GB' attribute only (this currently DOES return a row)
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
AND `attribute_option_id` = '19';
Any advice on the database design would be appreciated too
Note: I was thinking to have a new column within the 'prices' table that has the matching attribute_ids serialised - would this be not good for optimisation however (e.g would it be slower than the current method)
Since attribute_option_id is an atomic value, it cannot have two different values for the same row. So your WHERE clause cannot match any record:
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
AND `attribute_option_id` = '19' # Here for one row, attribute_option_id is either 19
AND `attribute_option_id` = '47'; # of '47'. Cannot be the both
Instead of JOIN, you could try a subquery if you feel that is more readable. I think MySQL allow that syntax:
SELECT `prices`.*
FROM `prices`
WHERE `prices`.`device_id` = '2939'
AND EXISTS (SELECT *
FROM prices_attributes
WHERE price_id = `prices`.`id`
AND attribute_option_id IN ('19', '47') )
I don't know how MySQL will optimize the above solution. An alternative would be:
SELECT `prices`.*
FROM `prices`
WHERE `prices`.`id` IN (
SELECT DISTINCT `price_id`
FROM prices_attributes
WHERE attribute_option_id IN ('19', '47')
)
I think you should use the IN operator for the attribute_option_id and you set the values dynamically to the query; Also, using group_by you have only one row per price so in effect you get all the prices. Apart from this, the design is ok.
Here, I have made an example:
SELECT `prices`.*
FROM (`prices`)
LEFT JOIN `prices_attributes` ON `prices_attributes`.`price_id` = `prices`.`id`
WHERE `prices`.`device_id` = '2939'
and `attribute_option_id` in ('19','47')
group by `prices`.`device_id`, `prices`.`price`;
Here, you can also add an order clause to order by price:
order by `prices`.`price` desc;
Another way to solve this would be to use a distinct on price, like this:
select distinct(prices.price)
from prices
where prices.device_id = 2939
and id in (select price_id from prices_attributes where attribute_option_id in (19,47));
Join against the devices_attributes_options table several times, once for each attribute the item must have
Something like this:-
SELECT *
FROM devices a
INNER JOIN prices b ON a.id = b.device_id
INNER JOIN prices_attributes c ON b.id = c.price_id
INNER JOIN devices_attributes_options d ON c.attribute_option_id = d.id AND d.attribute_value = '32GB'
INNER JOIN devices_attributes_options e ON c.attribute_option_id = e.id AND e.attribute_value = 'Black'
WHERE a.id = 2939
As to putting serialised details into a field, this is a really bad idea and would come back to bite you in the future!
SELECT * FROM prices WHERE device_id=2939 AND id IN (SELECT price_id FROM prices_attributes WHERE attribute_option_id IN (19,47));
Is it what you're looking for?
EDIT: sorry, didn't notice you're asking for query using joins
I need to check (from the same table) if there is an association between two events based on date-time.
One set of data will contain the ending date-time of certain events and the other set of data will contain the starting date-time for other events.
If the first event completes before the second event then I would like to link them up.
What I have so far is:
SELECT name as name_A, date-time as end_DTS, id as id_A
FROM tableA WHERE criteria = 1
SELECT name as name_B, date-time as start_DTS, id as id_B
FROM tableA WHERE criteria = 2
Then I join them:
SELECT name_A, name_B, id_A, id_B,
if(start_DTS > end_DTS,'VALID','') as validation_check
FROM tableA
LEFT JOIN tableB ON name_A = name_B
Can I then, based on my validation_check field, run a UPDATE query with the SELECT nested?
You can actually do this one of two ways:
MySQL update join syntax:
UPDATE tableA a
INNER JOIN tableB b ON a.name_a = b.name_b
SET validation_check = if(start_dts > end_dts, 'VALID', '')
-- where clause can go here
ANSI SQL syntax:
UPDATE tableA SET validation_check =
(SELECT if(start_DTS > end_DTS, 'VALID', '') AS validation_check
FROM tableA
INNER JOIN tableB ON name_A = name_B
WHERE id_A = tableA.id_A)
Pick whichever one seems most natural to you.
UPDATE
`table1` AS `dest`,
(
SELECT
*
FROM
`table2`
WHERE
`id` = x
) AS `src`
SET
`dest`.`col1` = `src`.`col1`
WHERE
`dest`.`id` = x
;
Hope this works for you.
Easy in MySQL:
UPDATE users AS U1, users AS U2
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id
If somebody is seeking to update data from one database to another no matter which table they are targeting, there must be some criteria to do it.
This one is better and clean for all levels:
UPDATE dbname1.content targetTable
LEFT JOIN dbname2.someothertable sourceTable ON
targetTable.compare_field= sourceTable.compare_field
SET
targetTable.col1 = sourceTable.cola,
targetTable.col2 = sourceTable.colb,
targetTable.col3 = sourceTable.colc,
targetTable.col4 = sourceTable.cold
Traaa! It works great!
With the above understanding, you can modify the set fields and "on" criteria to do your work. You can also perform the checks, then pull the data into the temp table(s) and then run the update using the above syntax replacing your table and column names.
Hope it works, if not let me know. I will write an exact query for you.
UPDATE
receipt_invoices dest,
(
SELECT
`receipt_id`,
CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat
FROM
receipt
WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total
AND vat_percentage = 12
) src
SET
dest.price = src.witoutvat,
dest.amount = src.witoutvat
WHERE col_tobefixed = 1
AND dest.`receipt_id` = src.receipt_id ;
Hope this will help you in a case where you have to match and update between two tables.
I found this question in looking for my own solution to a very complex join. This is an alternative solution, to a more complex version of the problem, which I thought might be useful.
I needed to populate the product_id field in the activities table, where activities are numbered in a unit, and units are numbered in a level (identified using a string ??N), such that one can identify activities using an SKU ie L1U1A1. Those SKUs are then stored in a different table.
I identified the following to get a list of activity_id vs product_id:-
SELECT a.activity_id, w.product_id
FROM activities a
JOIN units USING(unit_id)
JOIN product_types USING(product_type_id)
JOIN web_products w
ON sku=CONCAT('L',SUBSTR(product_type_code,3), 'U',unit_index, 'A',activity_index)
I found that that was too complex to incorporate into a SELECT within mysql, so I created a temporary table, and joined that with the update statement:-
CREATE TEMPORARY TABLE activity_product_ids AS (<the above select statement>);
UPDATE activities a
JOIN activity_product_ids b
ON a.activity_id=b.activity_id
SET a.product_id=b.product_id;
I hope someone finds this useful
UPDATE [table_name] AS T1,
(SELECT [column_name]
FROM [table_name]
WHERE [column_name] = [value]) AS T2
SET T1.[column_name]=T2.[column_name] + 1
WHERE T1.[column_name] = [value];
You can update values from another table using inner join like this
UPDATE [table1_name] AS t1 INNER JOIN [table2_name] AS t2 ON t1.column1_name] = t2.[column1_name] SET t1.[column2_name] = t2.column2_name];
Follow here to know how to use this query http://www.voidtricks.com/mysql-inner-join-update/
or you can use select as subquery to do this
UPDATE [table_name] SET [column_name] = (SELECT [column_name] FROM [table_name] WHERE [column_name] = [value]) WHERE [column_name] = [value];
query explained in details here http://www.voidtricks.com/mysql-update-from-select/
You can use:
UPDATE Station AS st1, StationOld AS st2
SET st1.already_used = 1
WHERE st1.code = st2.code
For same table,
UPDATE PHA_BILL_SEGMENT AS PHA,
(SELECT BILL_ID, COUNT(REGISTRATION_NUMBER) AS REG
FROM PHA_BILL_SEGMENT
GROUP BY REGISTRATION_NUMBER, BILL_DATE, BILL_AMOUNT
HAVING REG > 1) T
SET PHA.BILL_DATE = PHA.BILL_DATE + 2
WHERE PHA.BILL_ID = T.BILL_ID;
I had an issue with duplicate entries in one table itself. Below is the approaches were working for me. It has also been advocated by #sibaz.
Finally I solved it using the below queries:
The select query is saved in a temp table
IF OBJECT_ID(N'tempdb..#New_format_donor_temp', N'U') IS NOT NULL
DROP TABLE #New_format_donor_temp;
select *
into #New_format_donor_temp
from DONOR_EMPLOYMENTS
where DONOR_ID IN (
1, 2
)
-- Test New_format_donor_temp
-- SELECT *
-- FROM #New_format_donor_temp;
The temp table is joined in the update query.
UPDATE de
SET STATUS_CD=de_new.STATUS_CD, STATUS_REASON_CD=de_new.STATUS_REASON_CD, TYPE_CD=de_new.TYPE_CD
FROM DONOR_EMPLOYMENTS AS de
INNER JOIN #New_format_donor_temp AS de_new ON de_new.EMP_NO = de.EMP_NO
WHERE
de.DONOR_ID IN (
3, 4
)
I not very experienced with SQL please advise any better approach you know.
Above queries are for MySql server.
if you are updating from a complex query. The best thing is create temporary table from the query, then use the temporary table to update as one query.
DROP TABLE IF EXISTS cash_sales_sums;
CREATE TEMPORARY TABLE cash_sales_sums as
SELECT tbl_cash_sales_documents.batch_key, COUNT(DISTINCT tbl_cash_sales_documents.cash_sale_number) no_of_docs,
SUM(tbl_cash_sales_documents.paid_amount) paid_amount, SUM(A.amount - tbl_cash_sales_documents.bonus_amount - tbl_cash_sales_documents.discount_given) amount,
SUM(A.recs) no_of_entries FROM
tbl_cash_sales_documents
RIGHT JOIN(
SELECT
SUM(
tbl_cash_sales_transactions.amount
)amount,
tbl_cash_sales_transactions.cash_sale_document_id,
COUNT(transaction_id)recs
FROM
tbl_cash_sales_transactions
GROUP BY
tbl_cash_sales_transactions.cash_sale_document_id
)A ON A.cash_sale_document_id = tbl_cash_sales_documents.cash_sale_id
GROUP BY
tbl_cash_sales_documents.batch_key
ORDER BY batch_key;
UPDATE tbl_cash_sales_batches SET control_totals = (SELECT amount FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key LIMIT 1),
expected_number_of_documents = (SELECT no_of_docs FROM cash_sales_sums WHERE cash_sales_sums.batch_key = tbl_cash_sales_batches.batch_key),
computer_number_of_documents = expected_number_of_documents, computer_total_amount = control_totals
WHERE batch_key IN (SELECT batch_key FROM cash_sales_sums);
INSERT INTO all_table
SELECT Orders.OrderID,
Orders.CustomerID,
Orders.Amount,
Orders.ProductID,
Orders.Date,
Customer.CustomerName,
Customer.Address
FROM Orders
JOIN Customer ON Orders.CustomerID=Customer.CustomerID
WHERE Orders.OrderID not in (SELECT OrderID FROM all_table)