How to get join multiple queries - sql

In this http://sqlfiddle.com/#!6/aa0e17/4 as you can see id is primary key and auto incremented and values column is int type. To retrieve count based on value I am doing 4 different queries
select count(id) from status where value=1
select count(id )from status where value=2
select count(id) from status where value=3
select count(id) from status where value=4
My requirement is to get all those counts in a single query.
Why I want?
The above table is just a demo table and have only 4 queries but in my scenario I have 35 queries and so I have to do 35 methods in java.
Expected output: 4,,4,4,4 (1st query result, 2nd query result, 3rd query result, 4th query result)

select value, count(id)
from status
group by value

Here are the 2 normal ways of solving it:
Example 1 PIVOT:
SELECT [1] count1,[2] count2,[3] count3,[4] count4
FROM
(
SELECT id, value
FROM status
) p
PIVOT (COUNT(id) FOR [value] IN ([1], [2], [3], [4])) AS pvt
Use CONCAT if you want to combine the columns into one.
To do this, replace first row in first example with:
SELECT CONCAT([1],',',[2],',',[3],',',[4])
Example 2 CASE:
SELECT
COUNT(CASE WHEN value = 1 THEN 1 END) count1,
COUNT(CASE WHEN value = 2 THEN 1 END) count2,
COUNT(CASE WHEN value = 3 THEN 1 END) count3,
COUNT(CASE WHEN value = 4 THEN 1 END) count4
FROM status

You should better count rows and group by the value by the following query:
SELECT COUNT(*) FROM status GROUP BY value
or for a better description and look try this:
SELECT value, COUNT(*) AS COUNT FROM status GROUP BY value

Use UNION (or UNION ALL to preserve duplicate values) like:
select count(id) from status where value=1
UNION
select count(id )from status where value=2
UNION
select count(id) from status where value=3
UNION
select count(id) from status where value=4
Have a look at a similar question here: https://stackoverflow.com/a/6066234
[Edit 1]
Check the fiddle, it works on my machine ;) http://sqlfiddle.com/#!6/b89ef/1/0
Since I removed a (3) from the insert, you get 4,3 (I'm only selecting fours and threes here).
[Edit 2]
I did not catch the part where you wanted it all on one line.
Just wrap a SELECT around your statements like http://sqlfiddle.com/#!6/aa0e17/34/0:
select
(select count(id) from status where value=1),
(select count(id) from status where value=2),
(select count(id) from status where value=3),
(select count(id) from status where value=4)
;
And your result is one row with 4,4,4,4 as result.

If what you're looking for is a comma-delimited string, then this might be helpful:
WITH CTE(N) AS(
SELECT COUNT(ID) FROM STATUS WHERE VALUE=1 UNION ALL
SELECT COUNT(ID )FROM STATUS WHERE VALUE=2 UNION ALL
SELECT COUNT(ID) FROM STATUS WHERE VALUE=3 UNION ALL
SELECT COUNT(ID) FROM STATUS WHERE VALUE=4 UNION ALL
)
SELECT STUFF((
SELECT N', ' + CONVERT(VARCHAR(10), N)
FROM CTE FOR XML PATH(''), TYPE
).value('text()[1]','nvarchar(max)')
, 1 , 2 , N'')

Related

how to find all column records are same or not in group by column in SQL

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

Duplicate Counts - TSQL

I want to get All records that has duplicate values for SOME of the fields (i.e. Key columns).
My code:
CREATE TABLE #TEMP (ID int, Descp varchar(5), Extra varchar(6))
INSERT INTO #Temp
SELECT 1,'One','Extra1'
UNION ALL
SELECT 2,'Two','Extra2'
UNION ALL
SELECT 3,'Three','Extra3'
UNION ALL
SELECT 1,'One','Extra4'
SELECT ID, Descp, Extra FROM #TEMP
;WITH Temp_CTE AS
(SELECT *
, ROW_NUMBER() OVER (PARTITION BY ID, Descp ORDER BY (SELECT 0))
AS DuplicateRowNumber
FROM #TEMP
)
SELECT * FROM Temp_cte
DROP TABLE #TEMP
The last column tells me how many times each row has appeared based on ID and Descp values.
I want that row but I ALSO need another column* that indicates both rows for ID = 1 and Descp = 'One' has showed up more than once.
So an extra column* (i.e. MultipleOccurances (bool)) which has 1 for two rows with ID = 1 and Descp = 'One' and 0 for other rows as they are only showing up once.
How can I achieve that? (I want to avoid using Count(1)>1 or something if possible.
Edit:
Desired output:
ID Descp Extra DuplicateRowNumber IsMultiple
1 One Extra1 1 1
1 One Extra4 2 1
2 Two Extra2 1 0
3 Three Extra3 1 0
SQL Fiddle
You say "I want to avoid using Count" but it is probably the best way. It uses the partitioning you already have on the row_number
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ID, Descp
ORDER BY (SELECT 0)) AS DuplicateRowNumber,
CASE
WHEN COUNT(*) OVER (PARTITION BY ID, Descp) > 1 THEN 1
ELSE 0
END AS IsMultiple
FROM #Temp
And the execution plan just shows a single sort
Well, I have this solution, but using a Count...
SELECT T1.*,
ROW_NUMBER() OVER (PARTITION BY T1.ID, T1.Descp ORDER BY (SELECT 0)) AS DuplicateRowNumber,
CASE WHEN T2.C = 1 THEN 0 ELSE 1 END MultipleOcurrences FROM #temp T1
INNER JOIN
(SELECT ID, Descp, COUNT(1) C FROM #TEMP GROUP BY ID, Descp) T2
ON T1.ID = T2.ID AND T1.Descp = T2.Descp

Custom order after distinct statements

I want to make a custom order: IN, OUT, FINISHED.
If I left case statement I am getting in FINISHED, IN, OUT.
I found this solution but it does not work for me - I am getting error.
select distinct 'IN' as STATUS,
(select count(*) ...)
from table
UNION ALL
select distinct 'OUT',
(select count(*) ...)
from table
UNION ALL
select distinct 'FINISHED',
(select count(*) ...)
from table
order by
case STATUS
when 'IN' then 1
when 'OUT' then 2
when 'FINISHED' then 3
end
The query that you provided has some syntax irregularities. I think the following solves your problem:
select *
from ((select distinct 'IN' as statusA, (select count(*) ...
from table
)
union all
(select distinct 'OUT', (select count(*) ...)
from table
)
union all
(select distinct 'FINISHED', (select count(*) ...)
from table
)
) t
order by status,
(case STATUSA when 'IN' then 1
when 'OUT' then 2
when 'FINISHED' then 3
end)
Your original problem could have several causes. You were missing the 'IN' in the first subquery. You are missing the comma after status in the order by. And, some databases apply the final order by in a series of unions to only the last query (although I think DB2 does this correctly).

ORDER BY CASE does not working?

Hi I have SQL statement in DB2 which is working.
select distinct 'IN' as STATUS,
(select count(*) from table.......)
from table
UNION ALL
select distinct 'OUT',
(select count(*) from table.......)
from table
UNION ALL
select distinct 'FINISHED',
(select count(*) from table.......)
from table
order by status
But if I change the last line to
order by
case STATUS
when 'IN' then 1
when 'OUT' then 2
when 'FINISHED' then 3
end
My query does not work.
Can someone tell me how to solve this?
Thanks
Try wrapping the UNION into a derived table and order on that:
select *
from (
.... here goes your statement ...
) t
order by
case STATUS
when 'IN' then 1
when 'OUT' then 2
when 'FINISHED' then 3
end
you could always add the sort # to the status:
select distinct '1-IN' as STATUS,
(select count(*) from table.......)
from table
UNION ALL
select distinct '2-OUT',
(select count(*) from table.......)
from table
UNION ALL
select distinct '3-FINISHED',
(select count(*) from table.......)
from table
order by status
hello try this should work if i remember correctly
order by
case
when STATUS='IN' then 1
when STATUS='OUT' then 2
when STATUS='FINISHED' then 3
end
you could also name this when finishing
end as field_name

Counting the rows of a column where the value of a different column is 1

I am using a select count distinct to count the number of records in a column. However, I only want to count the records where the value of a different column is 1.
So my table looks a bit like this:
Name------Type
abc---------1
def----------2
ghi----------2
jkl-----------1
mno--------1
and I want the query only to count abc, jkl and mno and thus return '3'.
I wasn't able to do this with the CASE function, because this only seems to work with conditions in the same column.
EDIT: Sorry, I should have added, I want to make a query that counts both types.
So the result should look more like:
1---3
2---2
SELECT COUNT(*)
FROM dbo.[table name]
WHERE [type] = 1;
If you want to return the counts by type:
SELECT [type], COUNT(*)
FROM dbo.[table name]
GROUP BY [type]
ORDER BY [type];
You should avoid using keywords like type as column names - you can avoid a lot of square brackets if you use a more specific, non-reserved word.
I think you'll want (assuming that you wouldn't want to count ('abc',1) twice if it is in your table twice):
select count(distinct name)
from mytable
where type = 1
EDIT: for getting all types
select type, count(distinct name)
from mytable
group by type
order by type
select count(1) from tbl where type = 1
;WITH MyTable (Name, [Type]) AS
(
SELECT 'abc', 1
UNION
SELECT 'def', 2
UNION
SELECT 'ghi', 2
UNION
SELECT 'jkl', 1
UNION
SELECT 'mno', 1
)
SELECT COUNT( DISTINCT Name)
FROM MyTable
WHERE [Type] = 1