I am having some strange issue with the SQL statement below. The result groups by user IDs and some of them turn out right but for one of them (user ID = 1) the "initial_average" is multiplied by 3. I really have no idea why.. Is there something wrong with the structure of the statement? If it is not clear, the aim is to sum the field "initial_avg" in the "tasks" table and have it broken out by user. Some help with this is much appreciated. I am using MySQL.
SELECT sum(initial_avg) AS initial_average
, sum(initial_std) AS initial_standard_dev
, tasks.user
, hourly_rate
FROM tasks
INNER JOIN user_project
ON tasks.user=user_project.user
AND tasks.project=59
AND tasks.user=1
GROUP BY tasks.user
I just solved it by adding another "and" clause (AND user_project.project=59 )
Optimize your query (Try it):
SELECT SUM(initial_avg) AS initial_average, SUM(initial_std) AS initial_standard_dev, tasks.user, hourly_rate FROM tasks INNER JOIN user_project ON tasks.user = user_project.user AND tasks.project = User_project.project WHERE tasks.project = 59 AND tasks.user = 1 GROUP BY tasks.user, hourly_rate
Related
Good day,
I have a small issue with MySQL Distinct.
Trying the following query in my system :
SELECT DISTINCT `booking_id`, `booking_ticket`, `booking_price`, `bookingcomment_id`, `bookingcomment_message` FROM `mysystem_booking`
LEFT JOIN `mysystem_bookingcomment` ON `mysystem_booking`.`booking_id` = `mysystem_bookingcomment`.`bookingcomment_link`
WHERE `booking_id` = 29791
The point is that there are bookings like 29791 that have many comments added.
Let's say 10. Then when running the above query I see 10 results instead of one.
And that's not the way DISTINCT supposes to work.
I simply want to know if there are any comments. If the comment ID is not 0 then there is a comment. Of course I can add COUNT(blabla) as comment_number but that's a whole different story. For me now I'd like just to have this syntax right.
You may try aggregating here, to find which bookings have at least a single comment associated with them:
SELECT
b.booking_id,
b.booking_ticket,
b.booking_price
FROM mysystem_booking b
LEFT JOIN mysystem_bookingcomment bc
ON b.booking_id = bc.bookingcomment_link
WHERE
b.booking_id = 29791
GROUP BY
b.booking_id
HAVING
COUNT(bc.bookingcomment_link) > 0;
Note that depending on your MySQL server mode, you might have to also add the booking_ticket and booking_price columns to the GROUP BY clause to get the above query to run.
You can try below - using a case when expression
SELECT DISTINCT `booking_id`, `booking_ticket`, `booking_price`, `bookingcomment_id`,
case when `bookingcomment_message`<>'0' then 'No' else 'Yes' end as comments
FROM `mysystem_booking`
LEFT JOIN `mysystem_bookingcomment` ON `mysystem_booking`.`booking_id` = `mysystem_bookingcomment`.`bookingcomment_link`
WHERE `booking_id` = 29791
I have been through a few other posts relating to my error, but none of the solutions seem to work. I'm fairly new to SQL so sorry if its something really simple. I have two tables
Movie Inventory - which has columns movie_title, onhand_qty, and replacement_price
NotFlix - which has subscriber_name, queue_nbr, and movie_title
I am trying to join the two tables to output the total replacement price cost per customer, but when I do it gives me the error titled above. Here is my code, thanks in advance for any help!
SELECT subscriber_name, SUM (replacement_price) as replacement
FROM
(SELECT NotFlix.subscriber_name, NotFlix.movie_title, NotFlix.queue_nbr, MovieInventory.replacement_price
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
)
GROUP BY subscriber_name;
You are missing an alias:
SELECT AliasNameHere.subscriber_name, SUM (AliasNameHere.replacement_price) as replacement
FROM
(SELECT NotFlix.subscriber_name as subscriber_name, NotFlix.movie_title, NotFlix.queue_nbr, MovieInventory.replacement_price as replacement_price
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
) AliasNameHere
GROUP BY subscriber_name;
I Just don't get why are you doing a temporary table in FROM clause, you could just do a basic INNER JOIN here and potientialy avoid problem with alias name :
SELECT NotFlix.subscriber_name, SUM (MovieInventory.replacement_price) as replacement
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
GROUP BY subscriber_name;
I want to create a report with the top 20 customers (based on revenue).
I am using the query:
SELECT dbo.CustTable.AccountNum
,dbo.dirpartytable.NAME
,dbo.hcmworker.PERSONNELNUMBER
,dbo.CustInvoiceJour.SALESBALANCE
,dbo.custinvoicejour.QTY
FROM dbo.CustTable
inner JOIN dbo.HCMWORKER ON dbo.HCMWORKER.RECID = dbo.CustTable.KEV_Worker
inner join dbo.custInvoiceJour on CustInvoiceJour.OrderAccount = CustTable.AccountNum
inner join dbo.dirpartytable on dirpartytable.recid = custtable.PARTY
where CustTable.KEV_Worker = '5633561745'
ORDER BY SalesBalanceMst DESC
I can't find the relation for the customer revenue, after all, that is how I want to sort the report. I am sorting on SalesBalanceMST right now while building the report. Also I am getting multiple records when executing this query.
What am i doing wrong?
EDIT: I now realize I am showing each Invoice Journal, how can I display the Total Revenue of the customer?
A similar search from AX 2012:
CustInvoiceJour CustInvoiceJour;
CustTable CustTable;
DirPartyTable DirPartyTable;
select forceLiterals generateonly sum(SalesBalanceMST), sum(Qty) from CustInvoiceJour
where CustInvoiceJour.OrderAccount == '102372200'
&& CustInvoiceJour.InvoiceDate > today()-365
join TableId from CustTable
group AccountNum
where CustTable.AccountNum == CustInvoiceJour.OrderAccount
join TableId from DirPartyTable
group Name
where DirPartyTable.RecId == CustTable.Party;
info(CustInvoiceJour.getSQLStatement());
This shows the following SQL:
SELECT SUM(T1.SALESBALANCEMST),SUM(T1.QTY),T2.ACCOUNTNUM,T3.NAME
FROM CUSTINVOICEJOUR T1
CROSS JOIN CUSTTABLE T2
CROSS JOIN DIRPARTYTABLE T3
WHERE (((T1.PARTITION=5637144576) AND (T1.DATAAREAID=N'xxx'))
AND ((T1.ORDERACCOUNT=N'102372200')
AND (T1.INVOICEDATE>{ts '2015-11-06 00:00:00.000'})))
AND (((T2.PARTITION=5637144576) AND (T2.DATAAREAID=N'xxx'))
AND (T2.ACCOUNTNUM=T1.ORDERACCOUNT))
AND ((T3.PARTITION=5637144576)
AND (T3.RECID=T2.PARTY))
GROUP BY T2.ACCOUNTNUM,T3.NAME
ORDER BY T2.ACCOUNTNUM,T3.NAME
What is different from your query:
no join on HcmWorker, as I do not have your custom field.
Using sum() to aggregate
selecting on InvoiceDate
selection on OrderAccount
selection on DataAreaId, really important for performance, implicit in AX
selection on Partition, really important for performance, implicit in AX
You cannot directly sort on a sum, but may on a nested SQL query.
I do not know exactly what is wrong in your query but perhaps this information can help you.
Check this standard report CustTopCustomersbyYTDSales, It has some good queries to do that.
https://technet.microsoft.com/en-us/library/hh389751.aspx
I need to write query that joins several tables and I need distinct value from one table based on max count().
These are my tables names and columns:
bands:
db|name|
releases_artists:
release_db|band_db
releases_styles
release_db|style
Relations between tables are (needed for JOINs):
releases_artists.band_db = bands.db
releases_styles.release_db = releases_artists.release_db
And now the query that I need to write:
SELECT b.name, most_common_style
LEFT JOIN releases_artists ra ON ra.band_db = b.db
and here I need to find the most common style from all band releases
JOIN(
SELECT DISTINCT style WHERE releases_styles.release_db = ra.release_db ORDER BY COUNT() DESC LIMIT 1
)
FROM bands b
WHERE b.name LIKE 'something'
This is just a non working example of what I want to accomplish. It would be great if someone could help me build this query.
Thanks in advance.
EDIT 1
Each artist from table bands can have multiple records from releases_artists table based on band_db and each release can have multiple styles from releases_styles based on release_db
So if I search for b.name LIKE '%ray%' it returns something similar to:
`bands`:
o7te|Ray Wilson
9i84|Ray Parkey Jr.
`releases_artists` for Ray Wilson:
tv5c|o7te (for example album `Change`)
78wz|o7te (`The Next Best Thing`)
nz7c|o7te (`Propaganda Man`)
`releases_styles`
tv5c|Pop
tv5c|Rock
tv5c|Alternative Pop/Rock
----
78wz|Rock
78wz|Pop
78wz|Classic Rock
I need style name that repeats mostly from all artist releases as this artist main style.
Ok, this is a bit of a hack. But the only alternatives I could think of involve heaps of nested subqueries. So here goes:
SELECT name
, SUBSTRING_INDEX(GROUP_CONCAT(style ORDER BY release_count DESC SEPARATOR '|'), '|', 1) AS most_common_style
FROM (
SELECT b.db
, b.name
, rs.style
, COUNT(*) AS release_count
FROM bands b
JOIN releases_artists ra ON ra.band_db = b.db
JOIN releases_styles rs ON rs.release_db = ra.release_db
GROUP BY b.db, rs.style
) s
GROUP BY db;
I'm having some trouble with a SQL query across 3 tables with different attributes. Here are the tables and the attributes that I'd like to query in each of them:
news_stories - time, headline
per_minute_quotes - security_id, timestamp, last_price
securities - name, id_bb, id
What I'd like to do is retrieve a security name, id from the securities table, find headlines that correspond to that security (with a timestamp) from the *news_stories* table and find the last_price for that security at the same time as the article from the per_minute_quotes table.
Does this make sense? Please see what I've managed to do so far below...
SELECT DISTINCT
`news_stories`.`time`
, `securities`.`name`
, `adjusted_daily_quotes`.`security_id`
, `news_stories`.`headline`
, `securities`.`id_bb`
, `securities`.`id`
FROM
`schema`.`adjusted_daily_quotes`
, `schema`.`securities`
, `schema`.`news_stories`
WHERE ( (`adjusted_daily_quotes`.`security_id`) = '498'
AND (`securities`.`id`) = '498'
AND (`securities`.`id_bb`) LIKE '267%'
AND (`news_stories`.`headline`) LIKE '%:267')
LIMIT 0,50;
This will basically do the first part of my query, ie. it isn't connected with the last_price. Here is my attempt at doing that:
SELECT DISTINCT
`news_stories`.`time`
, `securities`.`name`
, `per_minute_quotes`.`security_id`
, `news_stories`.`headline`
, `securities`.`id_bb`
, `securities`.`id`
, `per_minute_quotes`.`timestamp`
, `per_minute_quotes`.`last_price`
FROM
`schema`.`per_minute_quotes`
, `schema`.`securities`
, `schema`.`news_stories`
WHERE ( (`per_minute_quotes`.`security_id`) = '498'
AND (`securities`.`id`) = '498'
AND (`securities`.`id_bb`) LIKE '267%'
AND (`news_stories`.`headline`) LIKE '%:267 HK'
AND (`per_minute_quotes`.`timestamp`) <= (`news_stories`.`time`))
LIMIT 0,5;
However, this query returns 5 of the same headline for some reason, all with the same time. I would really appreciate help with forming this query. Does that have something to do with the DISTINCT operator? I've tried using GROUP BY but with no luck.
Thanks in advance!
This is probably by far the easiest way to do it / explain it, although there are other ways.
SELECT
s.name
, s.id
, ns.headline
, pmq.last_price
FROM
securities s
JOIN
news_stories ns
ON ns.headline LIKE '%:267 HK%'
JOIN
(
SELECT
MAX(per_minute_quotes.timestamp) ts
, per_minute_quotes.security_id
FROM
per_minute_quotes
WHERE
per_minute_quotes.security_id
AND per_minute_quotes.timestamp <= news_stories.time
GROUP BY
per_minute_quotes.security_id
) t1
JOIN
per_minute_quotes pmq
ON s.id = pmq.security_id
AND t1.ts = pmq.time
WHERE
security.id = '498'
LIMIT 0,5;
The easiest way to do this is with joins, which you are doing, it's just a different way. The other important thing you need, is the join with the aggregation in it (MAX). This join is a sub-query that finds the pmq with the MAX timestamp that is less or equal to when your news story was published. You were pretty close, just need a bit of refactoring.
*I may have mistakes in here as I typed it in Notepad and copy and pasted... and it's 4 AM and I should be in bed.