I'm getting this error
Column 'tbl_user.u_id' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
When I'm doing this query
SELECT *
FROM
tbl_user
JOIN
tbl_assign_role ON tbl_user.u_id = tbl_assign_role.tar_owner_id
WHERE
is_active = 1
AND u_id != 1
AND tar_is_deleted = 0
GROUP BY
tbl_assign_role.tar_owner_id
ORDER BY
tbl_user.u_updated_date DESC
Strongly agreed with #Dai
According to me, you should read first the role of "Group By". Here in your query there is no any aggregate function used, so there is no case here to use "Group By".
Do this, to continue removing duplicates while not needing the group by:
SELECT DISTINCT --[INSERT NEEDED COLUMNS HERE]
FROM
tbl_user
JOIN
tbl_assign_role ON tbl_user.u_id = tbl_assign_role.tar_owner_id
WHERE
is_active = 1
AND u_id != 1
AND tar_is_deleted = 0
ORDER BY
tbl_user.u_updated_date DESC
Related
First when I started this project seemed very simple. Two tables, field tbl1_USERMASTERID in Table 1 should be update from field tbl2_USERMASTERID Table 2. After I looked deeply in Table 2, there is no unique ID that I can use as a key to join these two tables. Only way to match the records from Table 1 and Table 2 is based on FIRST_NAME, LAST_NAME AND DOB. So I have to find records in Table 1 where:
tbl1_FIRST_NAME equals tbl2_FIRST_NAME
AND
tbl1_LAST_NAME equals tbl2_LAST_NAME
AND
tbl1_DOB equals tbl2_DOB
and then update USERMASTERID field. I was afraid that this can cause some duplicates and some users will end up with USERMASTERID that does not belong to them. So if I find more than one record based on first,last name and dob those records would not be updated. I would like just to skip and leave them blank. That way I wouldn't populate invalid USERMASTERID. I'm not sure what is the best way to approach this problem, should I use SQL or ColdFusion (my server side language)? Also how to detect more than one matching record?
Here is what I have so far:
UPDATE Table1 AS tbl1
LEFT OUTER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.fname = tbl2.fname
AND tbl1.lname = tbl2.lname
SET tbl1.usermasterid = tbl2.usermasterid
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
Here is query where I tried to detect duplicates:
SELECT DISTINCT
tbl1.FName,
tbl1.LName,
tbl1.dob,
COUNT(*) AS count
FROM Table1 AS tbl1
LEFT OUTER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.FName = tbl2.first
AND tbl1.LName = tbl2.last
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
AND LTRIM(RTRIM(tbl1.first)) <> ''
AND LTRIM(RTRIM(tbl1.last)) <> ''
AND LTRIM(RTRIM(tbl1.dob)) <> ''
GROUP BY tbl1.FName,tbl1.LName,tbl1.dob
Some data after I tested query above:
First Last DOB Count
John Cook 2008-07-11 2
Kate Witt 2013-06-05 1
Deb Ruis 2016-01-22 1
Mike Bennet 2007-01-15 1
Kristy Cruz 1997-10-20 1
Colin Jones 2011-10-13 1
Kevin Smith 2010-02-24 1
Corey Bruce 2008-04-11 1
Shawn Maiers 2016-08-28 1
Alenn Fitchner 1998-05-17 1
If anyone have idea how I can prevent/skip updating duplicate records or how to improve this query please let me know. Thank you.
You could check for and avoid duplicate matches using with common_table_expression (Transact-SQL)
along with row_number()., like so:
with cte as (
select
t.fname
, t.lname
, t.dob
, t.usermasterid
, NewUserMasterId = t2.usermasterid
, rn = row_number() over (partition by t.fname, t.lname, t.dob order by t2.usermasterid)
from table1 as t
inner join table2 as t2 on t.dob = t2.dob
and t.fname = t2.fname
and t.lname = t2.lname
and ltrim(rtrim(t.usermasterid)) = ''
)
--/* confirm these are the rows you want updated
select *
from cte as t
where t.NewUserMasterId != ''
and not exists (
select 1
from cte as i
where t.dob = i.dob
and t.fname = i.fname
and t.lname = i.lname
and i.rn>1
);
--*/
/* update those where only 1 usermasterid matches this record
update t
set t.usermasterid = t.NewUserMasterId
from cte as t
where t.NewUserMasterId != ''
and not exists (
select 1
from cte as i
where t.dob = i.dob
and t.fname = i.fname
and t.lname = i.lname
and i.rn>1
);
--*/
I use the cte to extract out the sub query for readability. Per the documentation, a common table expression (cte):
Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement.
Using row_number() to assign a number for each row, starting at 1 for each partition of t.fname, t.lname, t.dob. Having those numbered allows us to check for the existence of duplicates with the not exists() clause with ... and i.rn>1
You could use a CTE to filter out the duplicates from Table1 before joining:
; with CTE as (select *
, count(ID) over (partition by LastName, FirstName, DoB) as IDs
from Table1)
update a
set a.ID = b.ID
from Table2 a
left join CTE b
on a.FirstName = b.FirstName
and a.LastName = b.LastName
and a.Dob = b.Dob
and b.IDs = 1
This will work provided there are no exact duplicates (same demographics and same ID) in table 1. If there are exact duplicates, they will also be excluded from the join, but you can filter them out before the CTE to avoid this.
Please try below SQL:
UPDATE Table1 AS tbl1
INNER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.fname = tbl2.fname
AND tbl1.lname = tbl2.lname
LEFT JOIN Table2 AS tbl3
ON tbl3.dob = tbl2.dob
AND tbl3.fname = tbl2.fname
AND tbl3.lname = tbl2.lname
AND tbl3.usermasterid <> tbl2.usermasterid
SET tbl1.usermasterid = tbl2.usermasterid
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
AND tbl3.usermasterid is null
I have written a query that returns the list of all customers that have ever made a purchase with the company I work for. The person for whom I am getting the data would like to know if a specific criteria is true for any of these orders.
select L.ParentLocation,
[Number of Orders] = count(distinct(T.Order))
from Table1 L
join Table2 T
on L.Location = T.Location
group by L.ParentLocation
However, the issue is complicated because I am already grouping by ParentLocation, and each ParentLocation has many normal Locations. So I am counting the number of unique orders at the location level, then grouping them by the ParentLocation.
I want to return 'TRUE' in the query if a field 'OrderDesc' contains "Toys" in ANY of the orders by ANY of the Locations owned by a ParentLocation. Is there a way to do this?
NOTE: Table2 contains the OrderDesc column.
Thanks for reading!
select
L.ParentLocation,
[Number of Orders] = count(distinct(T.Order)),
has_toys = max(case when t.OrderDesc like '%toys%' then 'TRUE' else '' end)
from Table1 L
inner join Table2 T
on L.Location = T.Location
group by
L.ParentLocation
I have a MySQL query and I ran it working fine but same query showing error in SQL Server.
SQL Server query:
SELECT
COUNT(*) cnt
FROM
(SELECT DISTINCT
tc_id, MAX(exn_time), STATUS
FROM
release_details a, tc_details b
WHERE
a.project = b.project
AND a.tc_id = b.tc_name
AND logicaldel = 0
AND a.project = 'test'
GROUP BY
tc_id, STATUS) a
WHERE
a.status = 'PASS';
Error:
No column name was specified for column 2 of 'a'.
How do I modify the above query?
Use the Alias name for your inner query.You are getting the MAX(exn_time) but not specified the name for that column that's why throwing the error. And you can use the Joins to the tables to make it more readable.
SELECT COUNT(*) cnt
FROM (
SELECT DISTINCT
tc_id,
MAX(exn_time) AS Maxtime ,
STATUS
FROM
release_details a JOIN tc_details b
ON a.project= b.project
AND a.tc_id = b.tc_name
WHERE
logicaldel = 0
AND a.project ='test'
GROUP BY
tc_id,
STATUS
) a
WHERE a.status='PASS';
You missed to give Alias name inside subquery
Also as mentioned by Marc_s you need to use proper Inner Join, keep the join condition ON clause and move the filter to where clause
SELECT Count(*) cnt
FROM (SELECT DISTINCT tc_id,
Max(exn_time) Max_exn_time,
STATUS
FROM release_details a
INNER JOIN tc_details b
ON a.project = b.project
AND a.tc_id = b.tc_name
WHERE a.project = 'test'
AND logicaldel = 0
GROUP BY tc_id,
STATUS) a
WHERE a.status = 'PASS';
Your issue is obviously that your second column in the resultset a doesn't have an alias.
You can rewrite the whole query to this for the same result:
SELECT
COUNT(DISTINCT tc_id) cnt
FROM
release_details a
JOIN
tc_details b
ON
a.project = b.project
AND a.tc_id = b.tc_name
WHERE
logicaldel = 0
AND a.project = 'test'
AND STATUS = 'PASS'
Since STATUS only can have the value 'PASS', MAX(exn_time) is not helping your counting, DISTINCT should not be used in the beginning of a SELECT when using group by like in your case, it is redundant
I'm trying to query how many transaction each loyaltyID column has in AnthemTxns_Jr and what the total of all of their transactions adds up to. Right now, when I run this script, it says,
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.AnthemTxns_JR.count", or the name is ambiguous
Code:
Select DISTINCT
dbo.ANTHEM_IDS_JR.loyaltyID,
dbo.ANTHEM_IDS_JR.Military_Type,,
dbo.ANTHEM_IDS_JR.Military_Date,
dbo.AnthemTxns_JR.count(CheckTotal),
dbo.AnthemTxns_JR.sum(CheckTotal)
From
dbo.ANTHEM_IDS_JR
JOIN
dbo.AnthemTxns_JR ON dbo.ANTHEM_IDS_JR.loyaltyID = dbo.AnthemTxns_JR.loyaltyID
WHERE
Military_Type = 'Active Duty'
AND ACTIVE = 1
AND datalength(dbo.ANTHEM_IDS_JR.Military_Date) > 0
ORDER BY
loyaltyID;
Try this... It looks like you have it a bit mixed up in the select statement
Select DISTINCT
dbo.ANTHEM_IDS_JR.loyaltyID,
dbo.ANTHEM_IDS_JR.Military_Type,
dbo.ANTHEM_IDS_JR.Military_Date,
count(dbo.AnthemTxns_JR.CheckTotal) as CheckTotalCount,
sum(dbo.AnthemTxns_JR.CheckTotal) as CheckTotalSum
From
dbo.ANTHEM_IDS_JR
JOIN
dbo.AnthemTxns_JR ON dbo.ANTHEM_IDS_JR.loyaltyID = dbo.AnthemTxns_JR.loyaltyID
WHERE
Military_Type = 'Active Duty'
AND ACTIVE = 1
AND datalength(dbo.ANTHEM_IDS_JR.Military_Date) > 0
Group by
dbo.ANTHEM_IDS_JR.loyaltyID,
dbo.ANTHEM_IDS_JR.Military_Type,
dbo.ANTHEM_IDS_JR.Military_Date
ORDER BY
loyaltyID;
I have two tables, Order and OrderItem. There is a one-to-many relationship on Order.Order_ID=OrderItem.Order_ID
I want a query to return a list showing the status of each Order, COMPLETE or INCOMPLETE.
A COMPLETE Order is defined as one where all the related OrderItem records have a non-NULL, non-empty value in the OrderItem.Delivery_ID field.
This is what I have so far:
SELECT Order.Order_ID, 'INCOMPLETE' AS Order_status
FROM Order
WHERE EXISTS
(SELECT *
FROM OrderItem
WHERE OrderItem.Order_ID=Order.Order_ID
AND (OrderItem.Delivery_ID IS NULL OR OrderItem.Delivery_ID=''))
UNION
SELECT Order.Order_ID, 'COMPLETE' AS Order_status
FROM Order
WHERE NOT EXISTS
(SELECT *
FROM OrderItem
WHERE OrderItem.Order_ID=Order.Order_ID
AND (OrderItem.Delivery_ID IS NULL OR OrderItem.Delivery_ID=''))
ORDER BY Order_ID DESC
It works, but runs a bit slow. Is there a better way?
(N.B. I've restated the problem for clarity, actual table and field names are different)
I would suggest you have a column status on your Order table and update the status to complete when all order items get delivered.
It will make simple your query to get status as well improve performance.
Put it into a subquery to try to make the case statement less confusing:
SELECT Order_ID,
CASE WHEN incomplete_count > 0 THEN 'INCOMPLETE' ELSE 'COMPLETE' END
AS Order_status
FROM ( SELECT o.Order_ID
,SUM( CASE WHEN OrderItem.Delivery_ID IS NULL OR OrderItem.Delivery_ID='' THEN 1 ELSE 0 END )
AS incomplete_count
FROM Order o
INNER JOIN OrderItem i ON (i.Order_ID = o.Order_ID)
GROUP by o.Order_ID
) x
ORDER BY ORder_ID DESC
The idea is to keep a counter every time you encounter a null item. If the sum is 0, there were no empty order items.
Try this one -
SELECT
o.Order_ID
, Order_status =
CASE WHEN ot.Order_ID IS NULL
THEN 'COMPLETE'
ELSE 'INCOMPLETE'
END
FROM dbo.[Order] o
LEFT JOIN (
SELECT DISTINCT ot.Order_ID
FROM dbo.OrderItem ot
WHERE ISNULL(ot.Delivery_ID, '') = ''
) ot ON ot.Order_ID = o.Order_ID