I am creating a column in a new table( Table B) called Number of different locations. This column is derived from two columns in a Table A - Customer and Location.
Sample Data from Table A .
Customer Location
Mr James Smith Los Angeles
Mr David Jones London
Mr James Smith Paris
So the pseudo code ?
[Number of Different Locations] =
CASE
When Customer has more than one location ( count greater than 1 of for distinct customer)
Then populate those entries as 'Y'
Else 'N'
Now I have tried a few ways to code the 1st condition but it does not work .
CASE
When EXISTS ( select distinct customer, count ( Location ) from Table B
group by customer)
then 'Y'
Else 'N'
What am I doing wrong ? All the values are coming out in resultant table as 'Y'
SELECT Customer, Location, [Number of different locations] =
CASE
When EXISTS ( select distinct customer, count ( Location ) from Table B
group by customer
having count(location)>1)
then 'Y'
Else 'N'
END
FROM [Table]
you didn't specify "Having > 1"
You don't really need a separate subselect for that. This can be handled entirely within a GROUP BY clause and using the count of locations to determine if there are multiple locations.
SELECT Customer
, MultipleLocations =
CASE WHEN COUNT(Location) > 1
THEN 'Y'
ELSE 'N'
END
FROM YourTable
GROUP BY
Customer
Should your table contain multiple records for a customer with the same location, you can add a DISTINCT clause to accomodate for this.
SELECT Customer
, MultipleLocations =
CASE WHEN COUNT(DISTINCT Location) > 1
THEN 'Y'
ELSE 'N'
END
FROM YourTable
GROUP BY
Customer
Maybe this will help did it in another way:
DECLARE #tbl TABLE
(
Customer VARCHAR(100),
Location VARCHAR(100)
)
INSERT INTO #tbl
SELECT 'Mr James Smith','Los Angeles'
UNION ALL
SELECT 'Mr David Jones','London'
UNION ALL
SELECT 'Mr James Smith','Paris'
;WITH CTE AS
(
SELECT
COUNT(*) OVER(PARTITION BY tbl.Customer) AS NbrOf,
tbl.Customer,
tbl.Location
FROM
#tbl AS tbl
)
SELECT
CTE.Customer,
CTE.Location,
(
CASE
WHEN CTE.NbrOf>1
THEN 'Y'
ELSE 'N'
END
) AS newColumn
FROM
CTE
WITH TableA
AS
(
SELECT *
FROM (
VALUES ('Mr James Smith', 'Los Angeles'),
('Mr David Jones', 'London'),
('Mr James Smith', 'Paris')
) AS T (Customer, Location)
),
TableACustomerTallies
AS
(
SELECT Customer, COUNT(DISTINCT Location) AS Tally
FROM TableA
GROUP
BY Customer
)
SELECT Customer,
'Y' AS HasMultipleLocations
FROM TableACustomerTallies
WHERE Tally > 1
UNION
SELECT Customer,
'N' AS HasMultipleLocations
FROM TableACustomerTallies
WHERE Tally <= 1;
Related
How to find all column values are same in Group by of rows in table
CREATE TABLE #Temp (ID int,Value char(1))
insert into #Temp (ID ,Value ) ( Select 1 ,'A' union all Select 1 ,'W' union all Select 1 ,'I' union all Select 2 ,'I' union all Select 2 ,'I' union all Select 3 ,'A' union all Select 3 ,'B' union all Select 3 ,'1' )
select * from #Temp
Sample Table:
How to find all column value of 'Value' column are same or not if group by 'ID' Column.
Ex: select ID from #Temp group by ID
For ID 1 - Value column records are A, W, I - Not Same
For ID 2 - Value column records are I, I - Same
For ID 3 - Value column records are A, B, 1 - Not Same
I want the query to get a result like below
When all items in the group are the same, COUNT(DISTINCT Value) would be 1:
SELECT Id
, CASE WHEN COUNT(DISTINCT Value)=1 THEN 'Same' ELSE 'Not Same' END AS Result
FROM MyTable
GROUP BY Id
If you're using T-SQL, perhaps this will work for you:
SELECT t.ID,
CASE WHEN MAX(t.RN) > 1 THEN 'Same' ELSE 'Not Same' END AS GroupResults
FROM(
SELECT *, ROW_NUMBER() OVER(PARTITION BY ID, VALUE ORDER BY ID) RN
FROM #Temp
) t
GROUP BY t.ID
Usally that's rather easy: Aggregate per ID and count distinct values or compare minimum and maximum value.
However, neither COUNT(DISTINCT value) nor MIN(value) nor MAX(value) take nulls into consideration. So for an ID having value 'A' and null, these would detect uniqueness. Maybe this is what you want or nulls don't even occur in your data.
But if you want nulls to count as a value, then select distinct values first (where null gets a row too) and count then:
select id, case when count(*) = 1 then 'same' else 'not same' end as result
from (select distinct id, value from #temp) dist
group by id
order by id;
Rextester demo: http://rextester.com/KCZD88697
I need to find the Non-Identical values are exist in a particular Group. Kindly have a look in the following Table Contact
ContactId FirstName LastName Mobile
_________________________________________________
1 Emma Watsan 9991234567
2 Jhon Wick 8887654321
1 Emma Watsan 9990001111
Here I need to fetch the Emma Watsan and need to find the Mobile numbers are Identical (bool - bit) If both Mobile numbers are Identical than 1 otherwise 0.
I tried the following Query
SELECT COUNT(*) FROM Contact c
GROUP BY c.ContactId, c.FirstName, c.LastName
HAVING COUNT(*) >1
Kindly assist me how to find the result.
for get the infor related to Emma Watsan you could ue
select * from Contact
where ContactId in (
select c.ContactId FROM Contact c
group by c.ContactId
having COUNT(*) >1
)
for get the Contacts that have the same numebr
select c.ContactId, COUNT(distinct Mobile) FROM Contact c
group by c.ContactId
having COUNT(distinct Mobile)>1
Use Count(Distinct [Mobile]) to get the number of distinct mobile nmumbers per ContactId. And the use a CASE expression to give 0 or 1 based of the count. If count is greater than 1 then 0 else 1.
Query
select t.[Name], case when t.[Mobile] > 1 then 0 else 1 end as [Mobile_Identity] from(
select ContactId,
max([FirstName] + ' ' + [LastName]) as [Name],
count(distinct [Mobile]) as [Mobile]
from contacts
group by ContactId
)t;
And if you want to retrieve only the rows with multiple mobile numbers, then use a having clause.
select t.[Name], case when t.[Mobile] > 1 then 0 else 1 end as [Mobile_Identity] from(
select ContactId,
max([FirstName] + ' ' + [LastName]) as [Name],
count(distinct [Mobile]) as [Mobile]
from contacts
group by ContactId
having count(distinct [Mobile]) > 1
)t;
Try This:
create table Contacts(ContactId int,FirstName varchar(15),LastName varchar(15),Mobile bigint)
insert into Contacts
select 1 ,'Emma','Watsan',9991234567
union all
select 2,'Jhon','Wick',8887654321
union all
select 1,'Emma','Watsan',9990001111
select c.ContactId, c.FirstName, c.LastName,IIF(cnt>1,1,0)ISIdentitcal
from (
SELECT c.ContactId, c.FirstName, c.LastName,
COUNT(*)cnt FROM Contacts c
GROUP BY c.ContactId, c.FirstName, c.LastName)c
How about:
Select distinct a.ContactId, case when b.mobile is null then 0 else 1 end as [is_duplicate]
from Contact a
left join Contact b
on a.ContactId = b.ContactId
and a.mobile = b.mobile
and a.id <> b.id
Where [id] is the primary key column in the table (you should have one).
Hope this helps.
PS: the table isn't normalized properly - if the ContactIDs repeat, the first and last name should not be in the same table.
I would do it something like this...(sample table variable with data included)
DECLARE #TABLE TABLE (ContactID INT, Firstname VARCHAR(55), Lastname VARCHAR(55), Mobile VARCHAR(55));
INSERT INTO #TABLE VALUES (1, 'Emma', 'Watsan', '9991234567');
INSERT INTO #TABLE VALUES (2, 'Jhon', 'Wick', '8887654321');
INSERT INTO #TABLE VALUES (1, 'Emma', 'Watsan', '9990001111');
INSERT INTO #TABLE VALUES (1, 'Emma', 'Watsan', '9990001111');
SELECT
T1.FirstName + ' ' + T1.LastName AS Name
,T1.Mobile
,MAX(CASE WHEN T2.RowID IS NULL THEN 0 ELSE 1 END) AS Duplicate
FROM
(
SELECT
ROW_NUMBER() OVER (ORDER BY FirstName,LastName, Mobile) AS RowID
,*
FROM #TABLE
) T1
LEFT JOIN
(
SELECT
ROW_NUMBER() OVER (ORDER BY FirstName,LastName, Mobile) AS RowID
,*
FROM #TABLE
) T2
ON T1.ContactID = T2.ContactID
AND T1.Mobile = T2.Mobile
AND T1.RowID <> T2.RowID
GROUP BY T1.FirstName + ' ' + T1.LastName, T1.Mobile
;
If the actual table already has row numbers, than the row_number() function can be skipped and the actual row ID of the table used in its place.
In the example here, Emma Watsan has the same number twice (on purpose), and another number that shows only once in the table. The duplicate mobile number is marked (Duplicate = 1), but the other numbers are not, as desired.
Need help for one query which is fetching result from multiple rows based on some condition. For e.g. we have table with [Roll no] with [subjects]. Table can have multiple records for the same [Roll No]. My requirement is if the Student opt for only 'English' then result should return 'E', if Maths then 'M' and if both then 'B'.
// I think this is what you want.
INSERT INTO dbo.rolls
( name, subject )
VALUES ( 'Jones', 'English'),
( 'Smith', 'Math'),
('Adams','English'),
('Adams', 'Math')
GO
;WITH CTE AS (
SELECT subquery1.name, 'B' AS code FROM (
SELECT name,COUNT(name) AS cnt
FROM rolls
WHERE subject = 'English' OR subject = 'Math'
GROUP BY name
HAVING COUNT(name) > 1 ) AS subquery1
UNION
SELECT subquery2.name, SUBSTRING(rolls.subject,1,1) AS code FROM (
SELECT name,COUNT(name) AS cnt
FROM rolls
WHERE subject = 'English' OR subject = 'Math'
GROUP BY name
HAVING COUNT(name) = 1 ) AS subquery2
INNER JOIN dbo.rolls
ON rolls.name = subquery2.name
)
SELECT * FROM CTE
I'm using SQL-Server 2008. I need to combine rows with the same Name and increase counter when:
1 or more Id's for the same Name is blank
NOT merge rows if Id is NULL!
NOT merge rows if have the same Name, but different Ids
Output for now:
Name Id Cnt
John 1 1
Peter 2 2 -- This Peter with the same Id have 2 entries so Cnt = 2
Peter 3 1 -- This is other Peter with 1 entry so Cnt = 1
Lisa 4 1
Lisa NULL 1
David 5 1
David 1 -- here Id is blank ''
Ralph 2 -- Ralph have both rows with blank Id so Cnt = 2
Desired output:
Name Id Cnt
John 1 1
Peter 2 2
Peter 3 1
Lisa 4 1
Lisa NULL 1 -- null still here
David 5 2 -- merged with blank '' so Cnt = 2
Ralph 2 -- merged both blanks '' so Cnt = 2
SQL-Query:
This is sample query what I'm using for now:
SELECT Name,
Id,
COUNT(Id) AS Cnt
FROM Employees
WHERE Condition = 1
GROUP BY Name, Id
What I have tried:
Added aggregate MAX to Id in SELECT clause and grouped by Name only, but in this case merged rows with NULL values and with the same names with different Id's what is wrong for me.
SELECT Name,
MAX(Id), -- added aggregate
COUNT(Id) AS Cnt
FROM Employees
WHERE Condition = 1
GROUP BY Name -- grouped by Name only
Have you any ideas? If anything is not clear about problem - ask me, I will provide more details.
UPDATE:
DDL
CREATE TABLE Employees
(
Name NVARCHAR(40),
Id NVARCHAR(40)
);
DML
INSERT INTO Employees VALUES
('John' , '1')
,('Peter', '2')
,('Peter', '2')
,('Peter', '3')
,('Lisa' , '4')
,('Lisa' , NULL)
,('David', '5')
,('David', '')
,('Ralph', '')
,('Ralph', '')
DEMO: SQL FIDDLE
Edit
DECLARE #Data table (Name varchar(10), Id varchar(10)) -- Id must be varchar for blank value
INSERT #Data VALUES
('John', '1'),
('Peter', '2'),('Peter', '2'),
('Peter', '3'),--('Peter', ''), --For test
('Lisa', '4'),
('Lisa', NULL),
('David', '5'),
('David', ''),
('Ralph', ''), ('Ralph', '')
SELECT
Name,
Id,
COUNT(*) + ISNULL(
(SELECT COUNT(*) FROM #data WHERE Name = d.Name AND Id = '' AND d.Id <> '')
, 0) AS Cnt
FROM #data d
WHERE
Id IS NULL
OR Id <> ''
OR NOT EXISTS(SELECT * FROM #data WHERE Name = d.Name AND Id <> '')
GROUP BY Name, Id
You can use CASE statement inside your SELECT. It allows you to set Id = [some value] for employees where it is blank. Query can be something like this:
SELECT E.Name,
CASE
WHEN E.Id = ''
THEN
(Select Employees.Id from Employees where Employees.Id <> '' and E.Name = Employees.Name)
ELSE E.Id
END as Idx,
COUNT(Id) AS Cnt
FROM Employees as E
WHERE Condition = 1
GROUP BY Name, Idx
A version with window functions:
SELECT Name,ID, Cnt from
( select *, sum(1-AmtBlank) over (partition by Name, ID) + sum(case id when 0 then 1 else 0 end) over (partition by Name) Cnt,
rank() over (partition by Name order by AmtBlank ) rnk,
row_number() over (partition by Name, ID order by AmtBlank) rnr
FROM (select * , case id when '' then 1 else 0 end AmtBlank from Employees /*WHERE Condition = 1*/ ) e
) c where rnr=1 and rnk = 1
This uses case id when '' then 1 else 0 end AmtBlank to keep an amount for the blank amounts per row (making the amount for non blanks 1-AmtBlank) and 2 window functions, one with id for a count per name and id (sum(1-AmtBlank) over (partition by Name, ID)) and a count for all blanks in a name section (sum(case id when 0 then 1 else 0 end) over (partition by Name))
The row_number is used to subsequently fetch only the first rows of a group and rank is used to only include the blank records when there are no records with an id.
Try this. using cte and joins
;with cte as (
SELECT Name,
Id,
COUNT(*) AS Cnt
FROM Employees
WHERE isnull(Id,1)<>''
GROUP BY Name, Id
),
cte2 as (SELECT Name,id, COUNT(*) AS Cnt FROM Employees WHERE Id='' GROUP BY Name,id)
select cte.Name,cte.Id,(cte.cnt + ISNULL(cte2.Cnt,0)) as cnt
from cte
left JOIN cte2
on cte.Name = cte2.Name
union all
select cte2.Name,cte2.Id,cte2.cnt
from cte2
left JOIN cte
on cte.Name = cte2.Name
where cte.Name is null
You could try something like this.
;WITH NonBlanks AS
(
SELECT Name,
Id,
COUNT(ISNULL(Id, 1)) AS Cnt
FROM Employees
WHERE ISNULL(Id,0) <> ''
GROUP BY Name, Id
)
,Blanks AS
(
SELECT Name,
Id,
COUNT(ISNULL(Id, 1)) AS Cnt
FROM Employees
WHERE ID = ''
GROUP BY Name, Id
)
SELECT CASE WHEN nb.NAME IS NULL THEN b.NAME ELSE nb.NAME END NAME,
CASE WHEN nb.NAME IS NULL THEN b.Id ELSE nb.Id END Id,
(ISNULL(nb.Cnt,0) + ISNULL(b.Cnt,0)) Cnt
FROM NonBlanks nb FULL JOIN Blanks b
ON nb.Name = b.Name
This simple syntax is compatible with older versions or other RDBMSs
-- Self explained on comments
edited:
select name, id, count(*) from (
-- adds "normal" records
select name, id from Employees where id is null or id <> ''
-- adds one record to each name-notBlankId for each blank id (David, Peter if you add 'Peter','')
-- uncomment /*or id is null*/ if you want even null ids to recieve merged blanks
union all
select e1.name, e1.id
from (select distinct name, id from Employees where id <> '' /*or id is null*/ ) as e1
inner join (select name, id from Employees where id = '') as e2 on e1.name = e2.name
-- adds records that can't be merged (Ralph)
union all
select name, id from Employees e1
where e1.id = ''
and not exists(select * from Employees e2 where e1.name = e2.name and e2.id <> '')
) as fullrecords
group by name, id
I can perform the following SQL Server selection of distinct (or non-repeating names) from a column in one table like so:
SELECT COUNT(DISTINCT [Name]) FROM [MyTable]
But what if I have more than one table (all these tables contain the name field called [Name]) and I need to know the count of non-repeating names in two or more tables.
If I run something like this:
SELECT COUNT(DISTINCT [Name]) FROM [MyTable1], [MyTable2], [MyTable3]
I get an error, "Ambiguous column name 'Name'".
PS. All three tables [MyTable1], [MyTable2], [MyTable3] are a product of a previous selection.
After the clarification, use:
SELECT x.name, COUNT(x.[name])
FROM (SELECT [name]
FROM [MyTable]
UNION ALL
SELECT [name]
FROM [MyTable2]
UNION ALL
SELECT [name]
FROM [MyTable3]) x
GROUP BY x.name
If I understand correctly, use:
SELECT x.name, COUNT(DISTINCT x.[name])
FROM (SELECT [name]
FROM [MyTable]
UNION ALL
SELECT [name]
FROM [MyTable2]
UNION ALL
SELECT [name]
FROM [MyTable3]) x
GROUP BY x.name
UNION will remove duplicates; UNION ALL will not, and is faster for it.
EDIT: Had to change after seeing recent comment.
Does this give you what you want? This gives a count for each person after combining the rows from all tables.
SELECT [NAME], COUNT(*) as TheCount
FROM
(
SELECT [Name] FROM [MyTable1]
UNION ALL
SELECT [Name] FROM [MyTable2]
UNION ALL
SELECT [Name] FROM [MyTable3]
) AS [TheNames]
GROUP BY [NAME]
Here's another way:
SELECT x.name, SUM(x.cnt)
FROM ( SELECT [name], COUNT(*) AS cnt
FROM [MyTable]
GROUP BY [name]
UNION ALL
SELECT [name], COUNT(*) AS cnt
FROM [MyTable2]
GROUP BY [name]
UNION ALL
SELECT [name], COUNT(*) AS cnt
FROM [MyTable3]
GROUP BY [name]
) AS x
GROUP BY x.name
In case you have different amounts of columns per table, like:
table1 has 3 columns,
table2 has 2 columns,
table3 has 1 column
And you want to count the amount of distinct values of different column names, what it was useful to me in AthenaSQL was to use CROSS JOIN since your output would be only one row, it would be just 1 combination:
SELECT * FROM (
SELECT COUNT(DISTINCT name1) as amt_name1,
COUNT(DISTINCT name2) as amt_name2,
COUNT(DISTINCT name3) as amt_name3,
FROM table1 ) t1
CROSS JOIN
(SELECT COUNT(DISTINCT name4) as amt_name4,
COUNT(DISTINCT name5) as amt_name5,
MAX(t3.amt_name6) as amt_name6
FROM table2
CROSS JOIN
(SELECT COUNT(DISTINCT name6) as amt_name6
FROM table3) t3) t2
Would return a table with one row and their counts:
amt_name1 | amt_name2 | amt_name3 | amt_name4 | amt_name5 | amt_name6
4123 | 675 | 564 | 2346 | 18667 | 74567