select count () how to add column - sql

This request gives me the count of the request occurrences where EMAIL occures.
select count(*)
from ADRESS K left outer join ADRESS L
on K.LFDNRSECONDADRESS=L.LFDNR
left outer join ADRESS V
on K.VERLFDNR=V.LFDNR
where ((UPPER(K.EMAIL)= 'my#email.com'
or exists (select ADRESSEMAILADR.LFDNR
from ADRESSEMAILADR
where ADRESSEMAILADR.ADRESSLFDNR=K.LFDNR
and UPPER(ADRESSEMAILADR.EMAIL)=
'my#email.com' )
)) and K.ART='K'
But I also would like go get all occurrences of the column "LFDNR".
Like
3
1234
2345
3456
...
So the first is the count and the followingup are the results of all columns where LFDNR = X.
Of cause I tried
LFDNR, select count(*)
K.LFDNR, select count(*)
And so on...
No luck so far.

If I understand correctly, you want group by:
select k.LFDNR, count(*)
from ADRESS K left outer join
ADRESS L
on K.LFDNRSECONDADRESS = L.LFDNR left outer join
ADRESS V
on K.VERLFDNR = V.LFDNR
where (UPPER(K.EMAIL)= 'my#email.com' or
exists (select ADRESSEMAILADR.LFDNR
from ADRESSEMAILADR
where ADRESSEMAILADR.ADRESSLFDNR = K.LFDNR and
UPPER(ADRESSEMAILADR.EMAIL) = 'my#email.com'
)
) and
K.ART = 'K'
group by k.LFDNR;

Related

Return Duplicate emails along with User Ids that are different

I'm running into an issue with a duplicate query and I hope you guys can help.
Essentially what I want to do is find and list of the duplicate emails associated with different userids
My query is:
select UserId, acitveid, email, userstatusid
from (select u.UserId, u.acitveid, cd.email, u.userstatusid,
count(*)over (partition by cd.email) as cnt
from ContactDetails cd
join UserContactDetails ucd on ucd.ContactDetailsId = cd.ContactDetailsId
join dbo.[User] u on u.UserId = ucd.UserId ) ua
where cnt >1
The issue I have with the above query is that it is returning the same userids for some of the results so it looks like:
Userid AcitveId email UserStatusid
123 1 abc#123.com 1
123 1 abc#123.com 1
135 1 efg#123.com 1
142 1 efg#123.com 1
The results Im looking for are simply:
Userid AcitveId email UserStatusid
135 1 efg#123.com 1
142 1 efg#123.com 1
WITH base AS (
SELECT DISTINCT u.UserId
,u.acitveid
,cd.email
,u.userstatusid
,
FROM ContactDetails cd
JOIN UserContactDetails ucd ON ucd.ContactDetailsId = cd.ContactDetailsId
JOIN dbo.[User] u ON u.UserId = ucd.UserId
)
,duplicate_emails AS (
SELECT email
,count(userId) AS cnt
FROM base
GROUP BY 1
HAVING count(userId) > 1
)
SELECT b.*
FROM base b
JOIN duplicate_emails de ON b.email = de.email
A self join across Email = email and id <> id would work fine here. That said, your request and lack of sample data means that we are largely guessing based off the query and sample output you have provided. The below should get you pretty close and, if you update your OP, I am sure we can get you exactly what you're after.
SELECT ActiveUser.UserID Active_UserID,
ActiveUser.ActiveID Active_ActiveID,
ContactDetails.email AS Email,
DuplicateUser.UserID AS Dup_UserID,
DuplicateUser.ActiveID As Dup_ActiveID
FROM ContactDetails INNER JOIN
ContactDetails AS Duplicate ON ContactDetails.email = Duplicate.email AND ContactDetails.UserID <> Duplicate.UserID INNER JOIN
UserContactDetails AS ActiveUserContactDetails ON ActiveUserContactDetails.ContactDetailsID = ContactDetails.ContactDetailsID INNER JOIN
dbo.[User] AS ActiveUser ON ActiveUser.UserID = ActiveUserContactDetails.UserID INNER JOIN
UserContactDetails AS DuplicateUserContactDetails ON DuplicateUserContactDetails.ContactDetailsID = Duplicate.ContactDetailsID INNER JOIN
dbo.[User] AS DuplicateUser ON DuplicateUser.UserID = UserContactDetails.UserID

Left join statement has no column 'client'

I am trying to append a column to the right
SELECT
'abc' as client,
sum(nested.freq) as freq,
FROM
(
SELECT
uh.route
COUNT(uh.route) as freq
FROM
employee AS up,
hist AS uh
where
up.id = uh.eID
AND uh.PrhEEBankRoute = '123'
GROUP BY
uh.route
) AS nested
LEFT JOIN (
SELECT
'abc' as client,
sum(raw.freq) as total_trans
FROM
(
SELECT
uh.route,
COUNT(uh.route) as freq
FROM
employee AS up,
hist AS uh
where
up.id = uh.eID
GROUP BY
uh.route
) AS raw
) raw2 ON raw2.client = nested.client;
The expected result is something like this
client | freq | total_trans
abc | 2 | 100
But I am getting the following error:
left join statement has no column 'client'
The first subquery, aliased as "nested" is:
SELECT
uh.route --<< no column called "client"
, COUNT(uh.route) AS freq --<< no column called "client"
FROM employee AS up
, hist AS uh
WHERE up.id = uh.eID
AND uh.PrhEEBankRoute = '123'
GROUP BY uh.route
In the next subquery at the join condition you refer to nested.client
) raw2 ON raw2.client = nested.client;
That column does not exist in the nested subquery, so the error message is accurate.

Fetching values from second table in the Query

select *
from EFLOVRelationship R
where R.parentEFLOVValueId = '5320'
and R.childEFLOVId in (select Eflovid
from EFFieldLOVStaticValue
where efLovId = 49)
In the above query I want to fetch 2 columns from EFFieldLOVStaticValue table and display.
Thanks in advance
Use Inner Join
SELECT R.*,
V.field1,
V.field2
FROM eflovrelationship R
INNER JOIN effieldlovstaticvalue V
ON R.childeflovid = V.eflovid
WHERE R.parenteflovvalueid = '5320'
AND V.eflovid = 49
If your table has 1:N relationship then use Distinct to avoid duplicates in result
If you want just one record from effieldlovstaticvalue table for each R.childeflovid column then use Cross Apply but you need to use required column to order the result and choose the top 1 record
SELECT R.*,
CS.field1,
CS.field2
FROM eflovrelationship R
CROSS apply (SELECT TOP 1 field1,
field2
FROM effieldlovstaticvalue V
WHERE R.childeflovid = V.eflovid
AND eflovid = 49
ORDER BY someordercolumn) CS
WHERE R.parenteflovvalueid = '5320'
Use join:
select R.*, sv.?, sv.?
from EFLOVRelationship R join
EFFieldLOVStaticValue sv
ON sv.Eflovid = R.childEFLOVId and sv.efLovId = 49
where R.parentEFLOVValueId = '5320'

Using the COUNT with multiple tables

I want to count the number of different sheep, and I want it in one table.
Like this;
Ewes | Rams | Lambs
8 | 5 | 12
The query I try is this, but it doesn't work;
SELECT COUNT(e.EweID) AS 'Ewe', COUNT(r.RamID) AS 'Ram', COUNT(l.LambID) AS 'Lamb'
FROM Sheep s
INNER JOIN Ewe e ON s.SheepID = e.EweID
INNER JOIN Ram r ON s.SheepID = r.RamID
INNER JOIN Lamb l ON s.SheepID = l.LambID
WHERE s.FarmerID = '123'
I don't get what I'm doing wrong, this is my database ERD;
I don't think you need a FROM here at all:
select
(select count(*) from Ram where Famerid = 123) as RamCount,
(select count(*) from Ewe where Famerid = 123) as Count,
(select count(*) from Lamb where Famerid = 123) as LambCount
(There is no relationship between the rows you are counting, do don't try and create one. Instead count each separately, wrapping it all in an outer select keeps everything in a single result row.)
I think that the problem here is that you don't need an INNER JOIN but an OUTER JOIN ...
SELECT COUNT(CASE WHEN e.EweID IN NOT NULL THEN e.EweID ELSE 0 END) AS 'Ewe', COUNT(r.RamID) AS 'Ram', COUNT(l.LambID) AS 'Lamb'
FROM Sheep s
LEFT OUTER JOIN Ewe e ON s.SheepID = e.EweID
LEFT OUTER JOIN Ram r ON s.SheepID = r.RamID
LEFT OUTER JOIN Lamb l ON s.SheepID = l.LambID
WHERE s.FarmerID = '123'
Take a look even at the case statement that I've added inside the first count(Ewe), to see a way to handle nulls in the count .
The Left Outer Join logical operator returns each row that satisfies
the join of the first (top) input with the second (bottom) input. It
also returns any rows from the first input that had no matching rows
in the second input. The nonmatching rows in the second input are
returned as null values. If no join predicate exists in the Argument
column, each row is a matching row.
Use correlated sub-selects to do the counting:
SELECT (select COUNT(*) from Ewe e where s.SheepID = e.EweID) AS 'Ewe',
(select COUNT(*) from Ram r where s.SheepID = r.RamID) AS 'Ram',
(select COUNT(*) from Lamb l where s.SheepID = l.LambID) AS 'Lamb'
FROM Sheep s
WHERE s.FarmerID = '123'
And you can also simply remove the WHERE clause to get all farms' counts.
DECLARE #Count1 INT;
SELECT #Count1 = COUNT(*)
FROM dbo.Ewe;
DECLARE #Count2 INT;
SELECT #Count2 = COUNT(*)
FROM dbo.Ram;
DECLARE #Count3 INT;
SELECT #Count3 = COUNT(*)
FROM dbo.Lamb;
SELECT #Count1 AS 'Ewe' ,
#Count2 AS 'Ram' ,
#Count3 AS 'Lamb'

MySql scoping problem with correlated subqueries

I'm having this Mysql query, It works:
SELECT
nom
,prenom
,(SELECT GROUP_CONCAT(category_en) FROM
(SELECT DISTINCT category_en FROM categories c WHERE id IN
(SELECT DISTINCT category_id FROM m3allems_to_categories m2c WHERE m3allem_id = 37)
) cS
) categories
,(SELECT GROUP_CONCAT(area_en) FROM
(SELECT DISTINCT area_en FROM areas c WHERE id IN
(SELECT DISTINCT area_id FROM m3allems_to_areas m2a WHERE m3allem_id = 37)
) aSq
) areas
FROM m3allems m
WHERE m.id = 37
The result is:
nom prenom categories areas
Man Multi Carpentry,Paint,Walls Beirut,Baalbak,Saida
It works correclty, but only when i hardcode into the query the id that I want (37).
I want it to work for all entries in the m3allem table, so I try this:
SELECT
nom
,prenom
,(SELECT GROUP_CONCAT(category_en) FROM
(SELECT DISTINCT category_en FROM categories c WHERE id IN
(SELECT DISTINCT category_id FROM m3allems_to_categories m2c WHERE m3allem_id = m.id)
) cS
) categories
,(SELECT GROUP_CONCAT(area_en) FROM
(SELECT DISTINCT area_en FROM areas c WHERE id IN
(SELECT DISTINCT area_id FROM m3allems_to_areas m2a WHERE m3allem_id = m.id)
) aSq
) areas
FROM m3allems m
And I get an error:
Unknown column 'm.id' in 'where
clause'
Why?
From the MySql manual:
13.2.8.7. Correlated Subqueries
[...]
Scoping rule: MySQL evaluates from inside to outside.
So... do this not work when the subquery is in a SELECT section? I did not read anything about that.
Does anyone know? What should I do? It took me a long time to build this query... I know it's a monster query but it gets what I want in a single query, and I am so close to getting it to work!
Can anyone help?
You can only correlate one level deep.
Use:
SELECT m.nom,
m.prenom,
x.categories,
y.areas
FROM m3allens m
LEFT JOIN (SELECT m2c.m3allem_id,
GROUP_CONCAT(DISTINCT c.category_en) AS categories
FROM CATEGORIES c
JOIN m3allems_to_categories m2c ON m2c.category_id = c.id
GROUP BY m2c.m3allem_id) x ON x.m3allem_id = m.id
LEFT JOIN (SELECT m2a.m3allem_id,
GROUP_CONCAT(DISTINCT a.area_en) AS areas
FROM AREAS a
JOIN m3allems_to_areas m2a ON m2a.area_id = a.id
GROUP BY m2a.m3allem_id) y ON y.m3allem_id = m.id
WHERE m.id = ?
The reason for the error is that in the subquery m is not defined. It is defined later in the outer query.