Doing a bit of investigation and writing a query against a logs db.
I've joined a number of tables to bring back the data that I need, but i'd like to clean it up a bit.
The query returns all the users and which features they have enabled on their account.
Here is what i'm trying to do to clean it up:
Their is a column called 'actions' which has two states, 'added' and 'removed'
If a user feature has an action of 'removed' then I want to not show any of the rows for the same feature for that user which are also marked as 'added'
Is this possible?!
Here is what I have so far:
select users.id as site_id, users.company_name, feature_log.featurecode, feature.minimum_account as feature_type, users.account_type as site_type, account_types.name as account, feature_log.action, feature_log.time
from users
inner join
feature_log
on users.id = feature_log.siteid
inner join
feature
on feature_log.featurecode = feature.featurecode
inner join account_types
on users.account_type_INC = account_types.id
where feature.minimum_account != 0
AND feature.minimum_account > users.account_type
AND users.status = 'Y'
ORDER BY feature_log.time DESC
Thanks for any support!
So, in order to "mute" all the features, that have been "removed" at any point in time for a given user, you can add a (left) join on the following subquery:
SELECT DISTINCT users.id as siteid, feature_log.featurecode, TRUE as mute_feature
FROM users
INNER JOIN feature_log ON (users.id = feature_log.siteid)
WHERE action = 'removed'
This will be the list of features that a given user disabled at some point in time. Then in your query's WHERE clause, you'd add a filter like so:
AND NOT IFNULL(mute_feature, FALSE)
Essentially, that'd bring your whole query to be:
select users.id as site_id, users.company_name, feature_log.featurecode, feature.minimum_account as feature_type, users.account_type as site_type, account_types.name as account, feature_log.action, feature_log.time
from users
inner join
feature_log
on users.id = feature_log.siteid
left join (
SELECT DISTINCT users.id as siteid, feature_log.featurecode, TRUE as mute_feature
FROM users
INNER JOIN feature_log ON (users.id = feature_log.siteid)
WHERE action = 'removed'
) as muted_features ON (feature_log.siteid = muted_features.siteid AND feature_log.featurecode = muted_features.featurecode)
inner join
feature
on feature_log.featurecode = feature.featurecode
inner join account_types
on users.account_type_INC = account_types.id
where feature.minimum_account != 0
AND feature.minimum_account > users.account_type
AND users.status = 'Y'
AND NOT IFNULL(mute_feature, FALSE)
ORDER BY feature_log.time DESC
Related
I am attempting to pass data from database to Google charts, however, Google charts has a specific way in which it excepts data. For this reason, I need to change the following output:
to this :
the query for the original output is:
SELECT (select COUNT(projects.funding)from projects where funding > 0)as Funding,
SUM(projects.mreq = 'yes') Mentor_Required,
SUM(projects.tmreq = 'yes') Team_Member_Required
FROM projects INNER JOIN users ON projects.members = users.email
WHERE users.company = 'vit'
The 2 tables are:
projects
users
Would love some guidance on putting pivot on the above query or any better method.
I think you can just do:
SELECT (CASE WHEN p.mreq = 'yes' THEN 'Mentor_Required'
WHEN p.tmreq = 'yes' THEN 'Team_Member_Required'
END) as Funding,
COUNT(*) as cnt
FROM projects p INNER JOIN
users u
ON p.members = u.email
WHERE u.company = 'vit'
GROUP BY Funding;
I have the following query for a report all is working fine, but I need to add a variable in the report that totals up the number of records for each record returned based off the number of records in the "manheim_auction_listings" record. I feel like it needs to be inside a join but everywhere I would the "COUNT(*) AS num_of_runs" it seems to make the whole query only return a single line with the count the total number of records in the query rather than all the lines with a variable num_of_runs with the number of "manheim_auction_listings" records for each CAR record.
SELECT products.client_id,
clients.name AS client_name,
manheim_auction_lanes.lane_number,
manheim_auction_listings.sequence,
manheim_auction_listings.gross_sale_price,
products.asking_price, products.asking_price_condition,
manheim_auctions.auction_date,
manheim_auctions.auction_number,
product_purchases.total_spent,
product_purchases.purchase_price
FROM manheim_auction_listings
JOIN cars ON
cars.id = manheim_auction_listings.car_id
JOIN products ON
cars.product_id = products.id
JOIN product_purchases ON
current_product_purchase_id = product_purchases.id
JOIN manheim_auctions ON
manheim_auctions.id = manheim_auction_listings.manheim_auction_id
JOIN manheim_auction_lanes ON
manheim_auction_lanes.id = manheim_auction_listings.manheim_auction_lane_id
JOIN clients ON
clients.id = products.client_id
AND clients.id LIKE $P{LoggedInUserAttribute_ClientID}
WHERE
manheim_auctions.auction_number = $P{SaleNumber}
AND manheim_auctions.`year` = $P{SaleYear}
ORDER BY manheim_auction_lanes.lane_number DESC,
manheim_auction_listings.sequence DESC
Please try the following...
SELECT products.client_id,
clients.name AS client_name,
manheim_auction_lanes.lane_number,
manheim_auction_listings.sequence,
manheim_auction_listings.gross_sale_price,
num_of_runs,
products.asking_price, products.asking_price_condition,
manheim_auctions.auction_date,
manheim_auctions.auction_number,
product_purchases.total_spent,
product_purchases.purchase_price
FROM ( SELECT manheim_auction_id AS manheim_auction_id,
COUNT( manheim_auction_id ) AS num_of_runs
FROM manheim_auction_listings
GROUP BY manheim_auction_id
) AS num_of_runs_finder
JOIN manheim_auction_listings ON manheim_auction_listings.manheim_auction_id = num_of_runs.manheim_auction_id
JOIN cars ON cars.id = manheim_auction_listings.car_id
JOIN products ON cars.product_id = products.id
JOIN product_purchases ON current_product_purchase_id = product_purchases.id
JOIN manheim_auctions ON manheim_auctions.id = manheim_auction_listings.manheim_auction_id
JOIN manheim_auction_lanes ON manheim_auction_lanes.id = manheim_auction_listings.manheim_auction_lane_id
JOIN clients ON clients.id = products.client_id
AND clients.id LIKE $P{LoggedInUserAttribute_ClientID}
WHERE manheim_auctions.auction_number = $P{SaleNumber}
AND manheim_auctions.`year` = $P{SaleYear}
ORDER BY manheim_auction_lanes.lane_number DESC,
manheim_auction_listings.sequence DESC
This works by joining your other tables to one that calculates the number of listings associated with each manheim_auction_id, effectively appending a manheim_auction_id's count to each row where that manheim_auction_id occurs.
If num_of_runs is calculated on some other criteria, then please advsie me accordingly.
If you have any questions or comments, then please feel free to post a Comment accordingly.
I am trying to add a contact person (T.ContactId) lookup to an existing query. The query uses a client id to get the client from the clients table. I now wish to add T.ContactId to get another name from the clients table. In the script below I have already added 'T.ContactId' to the select but I dont know how to continue from there
select T.Id Tid,Transdate,Quantity Unit,Amount Rate,Discount,T.Comment Comment,T.CmntToInvoice ConInv,T.JobNum JobNum,T.PayNum PayNum,T.ContactId,clients.Id `Id`,`Client`,Cell,Email,Yard,Horse,TransType `Transaction`,PayTypeId,Credit
from
transactions T,clients,yards,horses,transtypes
where
Pending = 'N' and
T.TransTypeId = transtypes.Id and
T.ClientId = clients.Id and
T.HorseId = horses.Id and
T.YardId = yards.Id and
Transdate between '2014-09-08' and '2016-07-08' and
T.JobNum = 0
order by
clients.Id,Transdate asc
You should change your implicit joins to explicit joins and add a second join to get the client id etc for t.contactid
Try this
select T.Id Tid,Transdate,Quantity Unit,Amount Rate,Discount,T.Comment Comment,T.CmntToInvoice ConInv,T.JobNum JobNum,T.PayNum PayNum,
T.ContactId,c1.id as 'ccid',c1.client as 'ContactCLient',
clients.Id `Id`,`Client`,Cell,Email,Yard,Horse,TransType `Transaction`,PayTypeId,Credit
from transactions T
join clients on T.ClientId = clients.Id
join yards on T.YardId = yards.Id
join horse on T.HorseId = horses.Id
join transtypes on T.TransTypeId = transtypes.Id
left outer join clients c1 on c1.id = t.contactid
where Pending = 'N' and
Transdate between '2014-09-08' and '2016-07-08' and
T.JobNum = 0
order by clients.Id,Transdate asc
I haven't tested this but if you can publish sample data and expected results then I would be happy to revisit.
So my database is composed of 5 tables with different columns for each one. The only column that keeps them all identified is the id. I'm trying to get the data for a specific user, but I only seem to get all users of the database instead.
This is what I have tried:
SELECT
ControlAccess.UserName,
ControlAccess.Pass,
Users.First_Name,
Users.Last_Name,
UserInfo.Age,
UserInfo.Country,
UserInfo.Address,
UserInfo.ZipCode,
Sessions.Matrix1,
Sessions.Matrix2,
Sessions.Result,
Operations.Operation,
FilePath.LocationFiles
FROM
MatrixUsers.UserInfo
INNER JOIN
MatrixUsers.Users
ON
UserInfo.idUserInfo = Users.idUsers = 1
INNER JOIN
MatrixUsers.ControlAccess
ON
ControlAccess.idControlAccess = UserInfo.idUserInfo = 1
INNER JOIN
MatrixUsers.Sessions
ON
Sessions.idSessions = ControlAccess.idControlAccess = 1
INNER JOIN
MatrixUsers.FilePath
ON
FilePath.idFilePath = Sessions.idSessions = 1
INNER JOIN
MatrixUsers.Operations
ON
Operations.idOperations = FilePath.idFilePath = 1;
I tried putting 1 at the end of each id to see if they matched, but I still get all the users.
I'm new to SQL and I'm only familiar with matching rows, but not choosing specific one.
Here are the columns of each table:
ControlAccess: {idControlAccess, UserName, Pass}
Sessions: {idSessions, Matrix1, Matrix2, Result}
FilePath: {idFilePath, LocationFiles}
Operations: {idOperation, Operation}
UserInfo: {idUserInfo, Age, Country, Address, ZipCode, Phone}
Use WHERE when you want specific user. for example, select user_id from table where user_id=the_specific_user_id . Follow this basic to built you complicate statement.
Just user where after all the joins
WHERE ANY_COLUMN_REFER_TO_USER_ID = YOUR_NEEDED_ID
so your full query would be like :
SELECT
ControlAccess.UserName,
ControlAccess.Pass,
Users.First_Name,
Users.Last_Name,
UserInfo.Age,
UserInfo.Country,
UserInfo.Address,
UserInfo.ZipCode,
Sessions.Matrix1,
Sessions.Matrix2,
Sessions.Result,
Operations.Operation,
FilePath.LocationFiles
FROM MatrixUsers.UserInfo
INNER JOIN MatrixUsers.Users
ON UserInfo.idUserInfo = Users.idUsers
INNER JOIN MatrixUsers.ControlAccess
ON ControlAccess.idControlAccess = UserInfo.idUserInfo
INNER JOIN MatrixUsers.Sessions
ON Sessions.idSessions = ControlAccess.idControlAccess
INNER JOIN MatrixUsers.FilePath
ON FilePath.idFilePath = Sessions.idSessions
INNER JOIN MatrixUsers.Operations
ON Operations.idOperations = FilePath.idFilePath
WHERE UserInfo.idUserInfo = 1
This query is for pulling down comments and replies if you can imagine a comment thread. The problem is that I needed to include a right join to include comments(These have null column values in reply columns). The problem is that it is pulling down all of the comment rows as you can see from this picture. Why is my filters for pageId, classId, albumId not correctly filtering?
SELECT rp.votes, cmts.pageId, cmts.content_element_id, rp.userId as replyUserId, (select users.firstName from users where users.guid = rp.userId) as replyFirstName,
(select users.lastName from users where users.guid = rp.userId) as replyLastName, rp.originalCommentId as replyOriginalCommentId,
rp.parentCommentId as replyParentCommentId, rp.commentId as replyCommentId, rp.text as replyText, rp.createdAt as replyCreatedAt,
rp.updatedAt as replyUpdatedAt, rp.status as replyStatus, cmts.classId as classId, cmts.albumId as albumId,
cmts.text as OriginalCommentText, cmts.status as CommentStatus, cmts.commentId as commentOriginalId,
cmts.createdAt as CommentCreatedAt, cmts.updatedAt as CommentUpdatedAt, cmts.status as cmtsStatus, cmts.userId as cmtsUserId, (select users.firstName from users where users.guid = cmts.userId) as commentFirstName, (select users.lastName from users where users.guid = cmts.userId) as commentLastName
FROM replies as rp
RIGHT JOIN comments as cmts ON rp.pageId = '36365094-0f52-49e3-bc0e-037edcca574b'
AND cmts.classId = '207'
AND cmts.albumId = '49152e6b-ca80-4889-a65e-4e6fd1dcc367'
AND rp.originalCommentId = cmts.commentId
ORDER BY cmts.createdAt
http://i59.tinypic.com/257q6wg.jpg
I cannot do an inner join, because it wont return the nulled values as seen from the picture.
#Gordon - I think I needed an extra and in there, like this: I'm double checking it now.
RIGHT JOIN comments cmts ON rp.pageId = '36365094-0f52-49e3-bc0e-037edcca574b'
AND rp.originalCommentId = cmts.commentId
WHERE cmts.classId = '207' AND cmts.albumId = '49152e6b-ca80-4889-a65e-4e6fd1dcc367' AND cmts.pageId = '36365094-0f52-49e3-bc0e-037edcca574b'
ORDER BY cmts.createdAt
You are filtering on the second table in the right join in the on clause. So, this does nothing. Add a where clause:
where cmts.classId = '207'AND cmts.albumId = '49152e6b-ca80-4889-a65e-4e6fd1dcc367'
to do the filtering.
A right join keeps all the rows in the second table, regardless of whether the on clause evaluates to "true", "false", or NULL. So, any filter on the second table is ignored.
(Note that for a left join, the same thing applies to the first table.)
EDIT:
The from clause would turn into:
FROM replies rp RIGHT JOIN
comments cmts
ON rp.pageId = '36365094-0f52-49e3-bc0e-037edcca574b' AND
rp.originalCommentId = cmts.commentId
WHERE cmts.classId = '207' AND
cmts.albumId = '49152e6b-ca80-4889-a65e-4e6fd1dcc367'