sql select inside count - without join - sql-server

There is a table called: IDs and another table called Entries.
Not all ids from Ids have entries. I do want to count how many entries have ALL the ids. if an Id has no entry I want to print 0.
Ids have PK: ID and Entries have a column ID.
If I joined them I get only the IDS having entries, but I want to get all of the IDS.

You are using INNER JOIN you can achieve this by using LEFT JOIN instead
EXAMPLE
/* Declare Temperory table for data storage */
DECLARE #MasterTable AS TABLE
(
ID INT
)
DECLARE #EntryTable AS TABLE
(
EntryID INT IDENTITY(1,1)
,MasterId INT
)
--Insert entries to Master Table
INSERT INTO #MasterTable
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
--Insert details into details table for only 1 and 2
INSERT INTO #EntryTable
(
MasterId
)
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 3
SELECT
ID
,COUNT(EntryTable.MasterId) AS EntryCount
FROM
#MasterTable MainTable
LEFT JOIN
#EntryTable EntryTable
ON
MainTable.ID = EntryTable.MasterId
GROUP BY
ID

Use a left join
select ids.id, count(entries.id)
from ids
left join entries on entries.id = ids.id
group by ids.id
Also see this great explanation of joins

SELECT DISTINCT id, EntriesCount.entriesCount
FROM IDs
OUTER APPLY (
SELECT COUNT(id) entriesCount
FROM Entries
WHERE Entries.ids = IDs.id
) AS EntriesCount
outer apply let's you use the id from IDs in the 'where' condition from Entries.

Related

T-SQL to select row count from two tables, excluding duplicates

So, I have 2 tables…. I need to get the combined row count from both, excluding any duplicates…
For example….
Table 1 has 20000 rows and Table 2 has 500 rows
There is 1 duplicate id that is in both table 1 and table 2, so the total row count should be 20,499….
This is what I have tried so far….
with cterc as
(SELECT COUNT(*) as rn
FROM Table_1 as t1
join Table_2 as t2 on t1.id <> t2.id)
SELECT SUM(rn) as totalrowNo
from cterc
Does the following provide your expected count?
select count(*)
from (
Select Id from Table_1
union /* distinct values, union all doesn't distinct values */
Select Id from Table_2
)t;

SQL Server : add a new column using union

I have 2 tables which have 2 columns in common and 1 column is different in both table
Table A
Table B
I need to create a common table having the values as follows
Expected Output
I tried using join on Memid and Meas but it duplicates as the 2 field do not create unique set as shown in figure
I tried union but then I get a resultset like this
Output for Inner join with distinct condition
How do I go about achieving the desired result set?
Note: Just a note coincidentally in this case the 2 columns seems to have similar values but they can be different.
Basically I need to create this one table with the 4 columns where Payer and PPayer columns should be independent of each other.
You don't need to use UNION, you can try like following using INNER JOIN.
INSERT INTO NewTable (
UserId
,DEPT
,ROOM
,LAB
)
SELECT DISTINCT ta.UserId
,ta.DEPT
,ta.ROOM
,tb.LAB
FROM TableA ta
INNER JOIN TableB tb ON ta.UserId = tb.UserId
AND ta.DEPT = tb.DEPT
Check Working Demo
Shanawaz Khan, Try this Solution
Declare Sample Table
DECLARE #A as TABLE(
UserId INT,
DEPT VARCHAR(50),
ROOM INT)
DECLARE #B as TABLE(
UserId INT,
DEPT VARCHAR(50),
LAB VARCHAR(50))
Insert Sample Records in Created Table
INSERT INTO #A (UserId,DEPT,ROOM) VALUES(1,'A',1),(1,'B',1),(1,'A',2),(1,'B',2)
INSERT INTO #B (UserId,DEPT,LAB) VALUES(1,'A','P'),(1,'B','Q'),(1,'A','P'),(1,'B','Q')
Generate DEPT wise Row number for Both Tables and Insert into another Temptable
SELECT ROW_NUMBER() OVER(PARTITION BY A.DEPT ORDER BY A.ROOM ) AS Rno,* INTO #tbl_A FROM #A A
SELECT ROW_NUMBER() OVER(PARTITION BY B.DEPT ORDER BY B.LAB) AS Rno,* INTO #tbl_B FROM #B B
Final Query Using Inner Join
SELECT A.UserId,A.DEPT,A.ROOM,B.LAB FROM #tbl_A AS A
INNER JOIN #tbl_B AS B ON A.Rno =B.Rno AND A.DEPT =B.DEPT ORDER BY A.ROOM, B.DEPT
Drop Created Temptable
DROP TABLE #tbl_A,#tbl_B
OutPut

SQL Remove row where value exist and subsequent column that has the value

I am trying to write a SQL statement that first gets only the distinct values of column 1, I then want to compare this with the same table but remove any rows that have a value in column 2
For example, the value 10142 in FieldID when I write a select that doesn't include 10142 it only removes the 1 row but also the subsequent ID column to have no rows.
So in the screenshot, I should only see all results for only ID 634 as 633 has the FieldID value 10142.
I tried initially getting a distinct ID value into a temporary table and then filtering in another select where the FieldID was not equal to 10142 but still not seeing the correct result.
This is my query:
SELECT DISTINCT id
INTO #TEMP
FROM tbl_WorkItemCustomLatest
ORDER BY ID ASC
SELECT a.*
FROM #TEMP
INNER JOIN dbo.tbl_WorkItemCustomLatest AS A ON #TEMP.id = A.id
WHERE A.FieldID != 10142
ORDER BY A.ID ASC
Any help is much appreciated.
With NOT EXISTS:
select t.* from tbl_WorkItemCustomLatest t
where not exists (
select 1 from tbl_WorkItemCustomLatest
where id = t.id and FieldId = 10142
)
or with NOT IN:
select * from tbl_WorkItemCustomLatest
where id not in (select id from tbl_WorkItemCustomLatest where FieldId = 10142)

How to test against a list of items in an if statement

I have a large table (130 columns). It is a monthly dataset that is separated by month (jan,feb,mar,...). every month I get a small set of duplicate rows. I would like to remove one of the rows, it does not matter which row to be deleted.
This query seems to work ok when I only select the ID that I want to filter the dups on, but when I select everything "*" from the table I end up with all of the rows, dups included. My goal is to filter out the dups and insert the result set into a new table.
SELECT DISTINCT a.[ID]
FROM MonthlyLoan a
JOIN (SELECT COUNT(*) as Count, b.[ID]
FROM MonthlyLoan b
GROUP BY b.[ID])
AS b ON a.[ID] = b.[ID]
WHERE b.Count > 1
and effectiveDate = '01/31/2017'
Any help will be appreciated.
This will show you all duplicates per ID:
;WITH Duplicates AS
(
SELECT ID
rn = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID)
FROM MonthlyLoan
)
SELECT ID,
rn
FROM Duplicates
WHERE rn > 1
Alternatively, you can set rn = 2 to find the immediate duplicate per ID.
Since your ID is dupped (A DUPPED ID!!!!)
all you need it to use the HAVING clause in your aggregate.
See the below example.
declare #tableA as table
(
ID int not null
)
insert into #tableA
values
(1),(2),(2),(3),(3),(3),(4),(5)
select ID, COUNT(*) as [Count]
from #tableA
group by ID
having COUNT(*) > 1
Result:
ID Count
----------- -----------
2 2
3 3
To insert the result into a #Temporary Table:
select ID, COUNT(*) as [Count]
into #temp
from #tableA
group by ID
having COUNT(*) > 1
select * from #temp

SUM from Select query then Show as another Column

I have this table that hold several products
And another table that holds the order for each product from above
How can i combine these tables and get the sum of each ord_Count per item and show it as another column, like this
To summarize it, I have a Items table that holds different products, and an Orders table that holds the orders for each product from the Items Table, then I want to have a query that combines both tables and show a my stock for each item from the Items table.
Try this:
SELECT SUM(ord_count) AS Item_stock, itm_Code
FROM YourTable
GROUP BY itm_Code
To combine both table:
SELECT SUM(B.ord_count) AS Item_stock, B.itm_Code
FROM YourTable1 AS A
INNER JOIN YourTable2 AS B
ON A.itm_Code = B.itm_Code
GROUP BY B.itm_Code
declare #t table (item varchar(20),itemcode varchar(20))
insert into #t (item,itemcode)values ('choco','ckschoc'),('chocowafer','wfrchoc'),('chocostrrae','wfrstr')
declare #tt table (ordcnt int,itemcode varchar(20),dated date)
insert into #tt (ordcnt,itemcode,dated)values (20,'ckschoc','4/24/2015'),(10,'wfrchoc','4/24/2015'),(15,'wfrstr','4/24/2015')
,(30,'ckschoc','4/24/2015'),(20,'wfrstr','4/24/2015')
we can achieve the same result using sub query and corelated join query also
Solution
select t.itemcode,p.S from #t t INNER JOIN (
select itemcode,SUM(ordcnt)S from #tt
GROUP BY itemcode)P
ON p.itemcode = t.itemcode
group by t.itemcode,P.s
select t.itemcode,
(select SUM(tt.ordcnt)Cnt from #tt tt
where tt.itemcode = t.itemcode
group by tt.itemcode )Cnt from #t t

Resources