I'm working on a social project and there are some tables which will have similar records which i'd like to group them into one. but with my query in brings all the records instead of grouping them into one.
SELECT
users_pics.email
, pic = MIN(pic)
, count(pic) AS total
,fname
,lname
,profile_pix
,RTRIM(wardrobe) as wardrobe
,gender
, resp_email
FROM
users_pics
INNER JOIN
profile
ON
users_pics.email = profile.email, dbo.viva_friends
WHERE
users_pics.stat = 'new'
AND
resp_email = MMColParam2
OR
req_email= MMColParam
AND
Status = 'Yes '
GROUP BY
users_pics.email
,fname,lname
,profile_pix
,wardrobe
,gender
,req_email
,resp_email
ORDER BY
MAX(users_pics.u_pic_id) DESC
please is there a way out. when i hit on the run button i get this.
Looks like you just want a simple GROUP BY;
SELECT users_pics.email, MIN(pic) AS pic, COUNT(pic) AS total, MAX(fname) AS fname,
MAX(lname) AS lname, MAX(profile_pix) AS profile_pic,
RTRIM(MAX(wardrobe)) AS wardrobe, MAX(gender) AS gender, MAX(resp_email) resp_email
FROM users_pics
INNER JOIN profile
ON users_pics.email = profile.email,
dbo.viva_friends
WHERE (users_pics.stat = 'new' AND resp_email = MMColParam2)
OR (req_email= MMColParam AND Status = 'Yes ')
GROUP BY
users_pics.email
Since I can't see your table structure, I can't tell what dbo.viva_friends is used for. It looks like it may be possible to just remove.
Related
I created a table column called name cause the firstname and the lastname are stored in two separate columns. To solve the problem I use CONCAT in the SELECT statement. However if I want to search for a specific value inside the name column SQL returns the error:
Unknown column 'name' in 'where clause'
Is it possible to search in a dynamically created column in a SELECT statement?
SELECT
u.ID AS id,
CONCAT(umFirstName.meta_value, " ", umLastName.meta_value) AS name,
u.user_email AS email,
umChatStatus.meta_value AS chatStatus,
umCallStatus.meta_value AS callStatus,
umRef.meta_value AS reference
FROM
wp_users AS u
LEFT JOIN
wp_usermeta AS um ON u.ID = um.user_id
LEFT JOIN
wp_usermeta AS umFirstName ON u.ID = umFirstName.user_id
AND umFirstName.meta_key = "_ctbFirstName"
LEFT JOIN
wp_usermeta AS umLastName ON u.ID = umLastName.user_id
AND umLastName.meta_key = "_ctbLastName"
LEFT JOIN
wp_usermeta AS umChatStatus ON u.ID = umChatStatus.user_id
AND umChatStatus.meta_key = "_ctbChatSessionStatus"
LEFT JOIN
wp_usermeta AS umCallStatus ON u.ID = umCallStatus.user_id
AND umCallStatus.meta_key = "_ctbCallSessionStatus"
LEFT JOIN
wp_usermeta AS umRef ON u.ID = umRef.user_id
AND umRef.meta_key = "_ctbRef"
WHERE
um.meta_key = "wp_capabilities"
AND um.meta_value IN ('a:1:{s:8:"employee ";b:1;}')
AND u.id LIKE '%%'
OR name LIKE '%%'
OR u.user_email LIKE '%%'
OR umChatStatus.meta_value LIKE '%%'
OR umCallStatus.meta_value LIKE '%%'
OR umRef.meta_value LIKE'%%'
ORDER BY
id DESC
LIMIT 0, 20
UPDATE
Got it working like it should. Thanks to Caius Jard metioning to -always use parentheses- in a AND and OR mix. For someone that is interested in the solution.
SQL queries are evaluated in the following order (just the blocks you've used):
FROM (including joins)
WHERE
SELECT
ORDER BY
This means that something you create in the SELECT, like CONCAT(Firstname, ' ', LastName) simply doesn't exist at the time the WHERE is evaluated
You have a couple of options:
Use CONCAT(Firstname, ' ', LastName) in the WHERE clause too
SELECT
CONCAT(Firstname, ' ', LastName) AS N
FROM
person
WHERE
CONCAT(Firstname, ' ', LastName) = 'John smith'
Turn the whole query into a sub query and use the thing you created in the outer
SELECT
x.N
FROM
(
SELECT
CONCAT(Firstname, ' ', LastName) AS N
FROM
person
) x
WHERE
x.N = 'John smith'
This form can also be written as:
WITH x AS
(
SELECT
CONCAT(Firstname, ' ', LastName) AS N
FROM
person
)
SELECT x.N
FROM x
WHERE x.N = 'John smith'
These latter forms are useful when you want to use it multiple times and don't want to keep repeating some massive calculation:
WITH x AS
(
SELECT
SUM(Points) / DATEDIFF(day, MIN(GameStart), MAX(GameEnd)) as PointsPerDay
FROM
Games
GROUP BY PlayerId
)
SELECT
CASE
WHEN PointsPerDay < 100 THEN 'Newbie'
WHEN PointsPerDay < 200 THEN 'Seasoned'
WHEN PointsPerDay < 300 THEN 'Advanced'
ELSE 'Pro'
END as Grading
FROM x
To have to keep repeating a calculation in order to do it all in one query is a bit ugly:
SELECT
CASE
WHEN SUM(Points) / DATEDIFF(day, MIN(GameStart), MAX(GameEnd)) < 100 THEN 'Newbie'
WHEN SUM(Points) / DATEDIFF(day, MIN(GameStart), MAX(GameEnd)) < 200 THEN 'Seasoned'
WHEN SUM(Points) / DATEDIFF(day, MIN(GameStart), MAX(GameEnd)) < 300 THEN 'Advanced'
ELSE 'Pro'
END as Grading
FROM
Games
GROUP BY PlayerId
And indeed because a GROUP BY is evaluated after a WHERE, if you want to use the result of a group by in a where you must do it as a "sub query that groups"/"outer query that wheres" pair
You can directly compare the concatenated value in the where clause like so:
CONCAT(umFirstName.meta_value, " ", umLastName.meta_value) LIKE '%abc%'
SELECT
u.ID AS id,
CONCAT(umFirstName.meta_value, " ", umLastName.meta_value) AS name,
u.user_email AS email,
umChatStatus.meta_value AS chatStatus,
umCallStatus.meta_value AS callStatus,
umRef.meta_value AS reference
FROM wp_users AS u
LEFT JOIN wp_usermeta AS um ON u.ID = um.user_id
LEFT JOIN wp_usermeta AS umFirstName ON u.ID = umFirstName.user_id AND
umFirstName.meta_key = "_ctbFirstName"
LEFT JOIN wp_usermeta AS umLastName ON u.ID = umLastName.user_id AND
umLastName.meta_key = "_ctbLastName"
LEFT JOIN wp_usermeta AS umChatStatus
ON u.ID = umChatStatus.user_id AND umChatStatus.meta_key = "_ctbChatSessionStatus"
LEFT JOIN wp_usermeta AS umCallStatus
ON u.ID = umCallStatus.user_id AND umCallStatus.meta_key = "_ctbCallSessionStatus"
LEFT JOIN wp_usermeta AS umRef ON u.ID = umRef.user_id AND umRef.meta_key = "_ctbRef"
WHERE um.meta_key = "wp_capabilities"
AND um.meta_value IN ('a:1:{s:8:"employee ";b:1;}')
AND u.id LIKE '%%'
OR CONCAT(umFirstName.meta_value, " ", umLastName.meta_value) LIKE '%%'
OR u.user_email LIKE '%%'
OR umChatStatus.meta_value LIKE '%%'
OR umCallStatus.meta_value LIKE '%%'
OR umRef.meta_value LIKE'%%'
ORDER BY id DESC
LIMIT 0, 20
I have some issues with duplicate SQL tables. When I run the query, I am looking to show the MOST recent “Order ID.” When I run the program, it will show me every single order ID from the company. I only want to pull the latest order ID. Is there something wrong with my query? Is there something I can add or remove?
I want to see the latest order number, currently I see them all.
SELECT DISTINCT
payee.id AS 'Carrier ID'
, payee.status AS 'Status'
, CASE
WHEN payee.status = 'I' THEN 0
WHEN payee.status = 'A' THEN 100
ELSE 0
END AS 'Active %'
, drs_payee.icc_number AS 'MC #'
, payee.name AS 'Name'
, CAST(drs_payee.liab_expire_date AS DATE) AS 'Liab Date'
, CAST(drs.payee.cargo_ins_renew_dt AS DATE) AS 'Cargo Date'
, CONCAT(contact.email,'; ' ,drs_payee.ins_expire_notify) AS 'Emails'
, orders.id AS 'Order ID'
--, CAST(stop.sched_arrive_early AS DATE) AS 'Delivery Date'
FROM payee
LEFT JOIN drs_payee ON payee.id = drs_payee.id
INNER JOIN contact ON payee.id = contact.parent_row_id
LEFT JOIN movement ON payee.id = movement.override_payee_id
LEFT JOIN orders ON orders.curr_movement_id = movement.id
LEFT JOIN stop ON movement.dest_stop_id = stop.sched_arrive_early
WHERE contact.sequence = '1'
Try to use ORDER BY [column_name] desc along with query and LIMIT if required.
Here's my query:
select
cast(ar.AudienceCreationDate as date) as AudienceDate,
Count(*) as [Count],
count(case when ar.Source = 'Contact' then ar.Id end) as PatientCount,
count(case when ar.Source = 'PatientContact' then ar.Id end) as PatientContactCount,
(
select
count(*)
from
_SMSMessageTracking sms
inner join
[CTT Preferences] pref on pref.ContactId = sms.SubscriberKey
where
sms.Name <> 'ky_ctt_join' and pref.Source = 'Patient'
) as PatientSMS,
(
select
count(*)
from
_SMSMessageTracking sms
inner join
[CTT Preferences] pref on pref.ContactId = sms.SubscriberKey
where
sms.Name <> 'ky_ctt_join' and pref.Source = 'PatientContact'
) as PatientContactSMS
from
Daily_Symptom_Check_Audience_Archive ar
group by
cast(ar.AudienceCreationDate as date)
And here's the result set it creates:
The issue I'm having is that the values in the rightmost two columns are the same across the board, for all records. This number represents the TOTAL, and not aggregated by day, as the other values indicate. I realize that I'm doing something wrong - what can I do to modify my query to effectively have a proper "grouping" on these last two columns just like all the other data in this table?
in the where clause of the nested query add sms.AudienceDate = ar.AudienceDate
select DAC.LocationCode, DAC.Description, ReqApp.Rank, App.Approver as UserName,
CASE WHEN app.Approver = app.AlternateApprover THEN ''
ELSE AltApp.AlternateApprover END As AltApprover,
ISNULL(CONVERT(Varchar,AltApp.FromDate,101),'')AS FromDate,
ISNULL(CONVERT(Varchar,AltApp.ToDate,101),'')AS ToDate
from tblAPAlternateApprovers App
INNER JOIN tblAPAlternateApprovers AltApp
ON App.ID = AltApp.ID
INNER JOIN tblAPReqLocations DAC
ON App.tblAPReqLocationsID = DAC.ID
INNER JOIN tblAPReqApprover ReqApp
ON App.Approver = ReqApp.Approver AND
App.tblAPReqLocationsID = ReqApp.LocationID
ORDER BY DAC.LocationCode ASC, ReqApp.Rank asc
Output
When SQL Adds an 'alternate approver' (for purchase orders), it creates an additional record for the actual approver. So, trying to find a way to show only 1 record for those approvers that also have alternates. i.e. 'jlhayes' has 2 records. One with an alternate and one without. For these records, I want to only see the ones that have an alternate.Thank you for your help. I've spend a couple hours and out of ideas.
You can wrap AltApprover case statement in max(AltApprover) and group by DAC.LocationCode, DAC.Description, ReqApp.Rank, App.Approver and do similarly for FromDate and ToDate:
select DAC.LocationCode, DAC.Description, ReqApp.Rank, App.Approver as UserName,
max(CASE WHEN app.Approver = app.AlternateApprover THEN ''
ELSE AltApp.AlternateApprover END) As AltApprover,
max(ISNULL(CONVERT(Varchar,AltApp.FromDate,101),'')) AS FromDate,
max(ISNULL(CONVERT(Varchar,AltApp.ToDate,101),'')) AS ToDate
from tblAPAlternateApprovers App
INNER JOIN tblAPAlternateApprovers AltApp
ON App.ID = AltApp.ID
INNER JOIN tblAPReqLocations DAC
ON App.tblAPReqLocationsID = DAC.ID
INNER JOIN tblAPReqApprover ReqApp
ON App.Approver = ReqApp.Approver AND
App.tblAPReqLocationsID = ReqApp.LocationID
GROUP BY DAC.LocationCode, DAC.Description, ReqApp.Rank, App.Approver
ORDER BY DAC.LocationCode ASC, ReqApp.Rank asc
I have this query in sql, and i can't get it right.
I'm trying to make a query to get the results from chat.
select message, first_name, last_name, dataPost,picture
from chat_comms
right join utilizadores
on (chat_comms.id_writer = utilizadores.id_user)
or (chat_comms.id_reader = utilizadores.id_user)
where id_writer = 1
or (id_reader = 1 and id_writer = 13)
order by dataPost ASC
RESULT
the first_name, last_name, picture, should be different because they are different users, how can i solve this?
SQL FIDDLE:
VIEW SQL FIDDLE
It looks like you have the duplicate rows because one of the users is the "writer" and the other is the "reader". I'm guessing that you actually want one row for each row in chat_comms linked to both the "writer" and "reader". In this case you need to join to utilizadores twice instead of using the or:
select message, writer.first_name, writer.last_name, dataPost, picture
from chat_comms
left join utilizadores writer on chat_comms.id_writer = writer.id_user
left join utilizadores reader on chat_comms.id_reader = reader.id_user
where id_writer = 1
or (id_reader = 1 and id_writer = 13)
order by dataPost ASC
This is just a guess because you haven't adequately described the result you're trying to achieve.
please verify below mentioned query:
SELECT message, first_name, last_name, dataPost,picture
FROM chat_comms
RIGHT JOIN utilizadores
ON chat_comms.id_writer = utilizadores.id_user
OR (chat_comms.id_reader = utilizadores.id_user)
WHERE id_writer = 1
order by dataPost ASC
Hope that helps, thanks.