I am trying to get row count in SQL Server 2008. I am using join which works perfect, I just want to get the total records because at the moment total records go beyond thousand.
select
tablet.Approach.ApproachId,StartDateTime,QuestionId
from
Tablet.Approach
join
tablet.DataCapture on tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
where
QuestionId = 25
So that I can see the existing result plus 1 extra field which displays total number of rows
You can achieve it like this -
Solution: 1
SELECT tablet.Approach.ApproachId
,StartDateTime
,QuestionId
,COUNT(*) OVER () AS TotalRowCount
FROM Tablet.Approach
JOIN tablet.DataCapture ON tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
WHERE QuestionId = 25
Solution: 2 (Using CTE)
;WITH SourceData
as
(
SELECT tablet.Approach.ApproachId
,StartDateTime
,QuestionId
FROM Tablet.Approach
JOIN tablet.DataCapture ON tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
WHERE QuestionId = 25
)
,RecordCnt
AS
(
SELECT COUNT(ApproachId) AS TotalRowCount
FROM SourceData
)
Select * from SourceData Cross join RecordCnt
try this
select
count(*),
tablet.Approach.ApproachId,StartDateTime,QuestionId
from Tablet.Approach
join tablet.DataCapture
on tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
where QuestionId = 25
group by tablet.Approach.ApproachId,StartDateTime,QuestionId
You can get the total number of records using window functions, in particular count():
select a.ApproachId, StartDateTime, QuestionId,
count(*) over () as TotalRows
from Tablet.Approach a join
tablet.DataCapture dc
on a.ApproachId = dc.ApproachId
where QuestionId = 25;
I also added table aliases. These make the query easier to write and to read.
SELECT COUNT(*),tablet.Approach.ApproachId,StartDateTime,QuestionId
FROM Tablet.Approach
JOIN tablet.DataCapture ON tablet.Approach.ApproachId = tablet.DataCapture.ApproachId
WHERE QuestionId = 25
GROUP BY tablet.Approach.ApproachId,StartDateTime,QuestionId
Related
I am trying to write a query to answer the question "What Pop Tart flavor is sold in the most stores?"
Here is my schema:
I have this attempt:
SELECT COUNT(*) AS CountOfStores, PTF.PopTartFlavor AS PopTartFlavor
FROM tKrogerStore_PopTartFlavor KSPTF
INNER JOIN tPopTartFlavor PTF
ON KSPTF.PopTartFlavorID = PTF.PopTartFlavorID
GROUP BY PTF.PopTartFlavor
ORDER BY CountOfStores DESC
but the query gives me this:
and I just want the first 2 rows because they both have a count of 2, but if I say TOP 1 I just get the first row with a count of 2 and I don't get both rows that have a count of 2. How do I get both rows that have the same count (2)?
you could try uisng having the count(*) = to the max result
SELECT COUNT(*) AS CountOfStores, PTF.PopTartFlavor AS PopTartFlavor
FROM tKrogerStore_PopTartFlavor KSPTF
INNER JOIN tPopTartFlavor PTF
ON KSPTF.PopTartFlavorID = PTF.PopTartFlavorID
GROUP BY PTF.PopTartFlavor
HAVING COUNT(*) = (
select max(CountOfStores)
from (
SELECT COUNT(*) AS CountOfStores, PTF.PopTartFlavor AS PopTartFlavor
FROM tKrogerStore_PopTartFlavor KSPTF
INNER JOIN tPopTartFlavor PTF
ON KSPTF.PopTartFlavorID = PTF.PopTartFlavorID
GROUP BY PTF.PopTartFlavor
) t
)
I would capture the binned count and the overall max count in the same subquery query (the latter using an aggregated windowed function), then in the outer query filter for when they're equal.
select CountOfStores, PopTartFlavor
from (
select CountOfStores = count(*),
maxCountOfStores = max(count(*)) over(),
PTF.PopTartFlavor
from #tKrogerStore_PopTartFlavor KSPTF
join #tPopTartFlavor PTF ON KSPTF.PopTartFlavorID = PTF.PopTartFlavorID
group by PTF.PopTartFlavor
) c
where countOfStores = maxCountOfStores
I have a Questions group table like follows:
ID, NAME, DESCRIPTION, VERSION_ID
Versions table columns are:
ID, NUMBER, VERSION_STATE
VERSION_STATE is an enumerated that can be 0, 1 or 2.
I need to select all questions group that its version has thevVERSION_STATE 0 or 1, but if there is a questions group with a VERSION_STATE = 0 I don't have to return the questions group with the VERSION_STATE = 1.
The simplest approach is:
SELECT distinct QG.id FROM healthsafety.hs_questions_group QG
LEFT OUTER JOIN (SELECT * FROM healthsafety.hs_version) VERSION
ON QG.VERSION_ID = VERSION.ID
WHERE
VERSION.VERSION_STATE=0
OR VERSION.VERSION_STATE=1
The problem is that this query returns all questions group with the VERSION_STATE 0 or 1. If I remove the or clause, and there are not questions groups with VERSION_STATE = 0, I need to return the questions groups with VERSION_STATE = 1.
I think that I need an if else or case statement but I am stucked. Any Idea?
Note that I have to implement this using criteria, so I need to use the simplest solution.
SELECT *
FROM (
SELECT OG.ID,OG.NAME,OG.DESCRIPTION,VERSION.ID,VERSION.NUMBER,VERSION.VERSION_STATE,ROW_NUMBER()OVER(PARTITION BY OG.ID ORDER BY VERSION.VERSION_STATE ASC) as INDICATOR
FROM healthsafety.hs_questions_group QG
LEFT OUTER JOIN
(SELECT * FROM healthsafety.hs_version) VERSION
ON QG.VERSION_ID = VERSION.ID
WHERE
VERSION.VERSION_STATE=0
OR VERSION.VERSION_STATE=1
) AS ABC
WHERE (ABC.VERSION_STATE = 0 and ABC.INDICATOR = 1)
OR (ABC.VERSION_STATE = 1 and ABC.INDICATOR = 1)
Using a common table expression and a union all where the second query uses not exists() to only return rows where version_state=1 when rows with version_state=0 do not exist.
;with cte as (
select qg.id, v.version_state
from healthsafety.hs_questions_group qg
inner join healthsafety.hs_version version v
on qg.version_id = v.id
where v.version_state in (0,1)
)
select id
from cte
where version_state = 0
union all
select qg.id
from cte
where version_state = 1
and not exists (
select 1
from cte
where version_state = 0
)
I have this two query
1.
select CL_Clients.cl_id,CL_Clients].cl_name,COUNT(*) AS number_of_orders
from CL_Clients,CLOI_ClientOrderItems
where CL_Clients.cl_id=CLOI_ClientOrderItems.cl_id
group by CL_Clients.cl_name,CL_Clients.cl_id
2.
select CL_Clients.cl_id,count(cloi_current_status) as dis
from CLOI_ClientOrderItems,CL_Clients
where cloi_current_status]='12'
and CL_Clients.cl_id=CLOI_ClientOrderItems.cl_id
group by CL_Clients.cl_name,CL_Clients.cl_id,CLOI_ClientOrderItems.cloi_current_status
i have this column i need to put count function and where condition
[cloi_current_status]
166
30
30
30
150
150
150
150
150
150
150
Quite simple, you just encapsulate the queries and give their result sets an alias and then do a JOIN between their aliases on the column that is common. (In the query below I assume you'll be joining by client id)
SELECT *
FROM (
SELECT CL_Clients.cl_id,
CL_Clients].cl_name,
COUNT(*) AS number_of_orders
FROM CL_Clients,
CLOI_ClientOrderItems
WHERE CL_Clients.cl_id = CLOI_ClientOrderItems.cl_id
GROUP BY CL_Clients.cl_name,
CL_Clients.cl_id
) A
INNER JOIN (
SELECT CL_Clients.cl_id,
count(cloi_current_status) AS dis
FROM CLOI_ClientOrderItems,
CL_Clients
WHERE cloi_current_status] = '12'
AND CL_Clients.cl_id = CLOI_ClientOrderItems.cl_id
GROUP BY CL_Clients.cl_name,
CL_Clients.cl_id,
CLOI_ClientOrderItems.cloi_current_status
) B
ON A.cl_id = B.cl_id
WHERE ...
GROUP BY ...
This will be treated as a separate result set, so you can also filter results with a WHERE or just a GROUP BY, just like in a normal SELECT.
UPDATE:
To answer the question in your comments, when you join two tables that have a column with the same value and use
SELECT * FROM A INNER JOIN B the * will show all columns returned by the join, meaning all columns from A and all columns from B, this is why you have duplicate columns.
If you want to filter the columns returned you can specifiy which columns you want returned. So, in your case, the top SELECT * can be replaced with
SELECT A.cl_id, A.cl_name, A.number_of_orders, B.dis so, your query becomes:
SELECT A.cl_id, A.cl_name, A.number_of_orders, B.dis
FROM (
SELECT CL_Clients.cl_id,
CL_Clients].cl_name,
COUNT(*) AS number_of_orders
FROM CL_Clients,
CLOI_ClientOrderItems
WHERE CL_Clients.cl_id = CLOI_ClientOrderItems.cl_id
GROUP BY CL_Clients.cl_name,
CL_Clients.cl_id
) A
INNER JOIN (
SELECT CL_Clients.cl_id,
count(cloi_current_status) AS dis
FROM CLOI_ClientOrderItems,
CL_Clients
WHERE cloi_current_status] = '12'
AND CL_Clients.cl_id = CLOI_ClientOrderItems.cl_id
GROUP BY CL_Clients.cl_name,
CL_Clients.cl_id,
CLOI_ClientOrderItems.cloi_current_status
) B
ON A.cl_id = B.cl_id
UPDATE #2:
For your last question, you need to GROUP BY at the end of the big query and use a HAVING condtion, like this:
GROUP BY A.cl_id, A.cl_name, A.number_of_orders, B.dis
HAVING COUNT(cloi_current_status) > 100
All depends on what data you are trying to get, but you can go about it like this.
SELECT Column_x, Column_y, etc..
FROM ClL_Clients a
JOIN (select CL_Clients.cl_id,CL_Clients].cl_name,COUNT(*) AS number_of_orders
from CL_Clients,CLOI_ClientOrderItems
where CL_Clients.cl_id=CLOI_ClientOrderItems.cl_id
group by CL_Clients.cl_name,CL_Clients.cl_id) b
on a.cl_id = b.cl_id
JOIN (select CL_Clients.cl_id,count(cloi_current_status) as dis
from CLOI_ClientOrderItems,CL_Clients
where cloi_current_status]='12'
and CL_Clients.cl_id=CLOI_ClientOrderItems.cl_id
group by CL_Clients.cl_name,CL_Clients.cl_id,CLOI_ClientOrderItems.cloi_current_status) c
on a.cl_id = c.cl_id
Group by BLAH BLAH
Hope this gets you in the right direction.
I have a query like this:
SELECT TV.Descrizione as TipoVers,
sum(ImportoVersamento) as ImpTot,
count(*) as N,
month(DataAllibramento) as Mese
FROM PROC_Versamento V
left outer join dbo.PROC_TipoVersamento TV
on V.IDTipoVersamento = TV.IDTipoVersamento
inner join dbo.PROC_PraticaRiscossione PR
on V.IDPraticaRiscossioneAssociata = PR.IDPratica
inner join dbo.DA_Avviso A
on PR.IDDatiAvviso = A.IDAvviso
where DataAllibramento between '2012-09-08' and '2012-09-17' and A.IDFornitura = 4
group by V.IDTipoVersamento,month(DataAllibramento),TV.Descrizione
order by V.IDTipoVersamento,month(DataAllibramento)
This query must always return something. If no result is produced a
0 0 0 0
row must be returned. How can I do this. Use a isnull for every selected field isn't usefull.
Use a derived table with one row and do a outer apply to your other table / query.
Here is a sample with a table variable #T in place of your real table.
declare #T table
(
ID int,
Grp int
)
select isnull(Q.MaxID, 0) as MaxID,
isnull(Q.C, 0) as C
from (select 1) as T(X)
outer apply (
-- Your query goes here
select max(ID) as MaxID,
count(*) as C
from #T
group by Grp
) as Q
order by Q.C -- order by goes to the outer query
That will make sure you have always at least one row in the output.
Something like this using your query.
select isnull(Q.TipoVers, '0') as TipoVers,
isnull(Q.ImpTot, 0) as ImpTot,
isnull(Q.N, 0) as N,
isnull(Q.Mese, 0) as Mese
from (select 1) as T(X)
outer apply (
SELECT TV.Descrizione as TipoVers,
sum(ImportoVersamento) as ImpTot,
count(*) as N,
month(DataAllibramento) as Mese,
V.IDTipoVersamento
FROM PROC_Versamento V
left outer join dbo.PROC_TipoVersamento TV
on V.IDTipoVersamento = TV.IDTipoVersamento
inner join dbo.PROC_PraticaRiscossione PR
on V.IDPraticaRiscossioneAssociata = PR.IDPratica
inner join dbo.DA_Avviso A
on PR.IDDatiAvviso = A.IDAvviso
where DataAllibramento between '2012-09-08' and '2012-09-17' and A.IDFornitura = 4
group by V.IDTipoVersamento,month(DataAllibramento),TV.Descrizione
) as Q
order by Q.IDTipoVersamento, Q.Mese
Use COALESCE. It returns the first non-null value. E.g.
SELECT COALESCE(TV.Desc, 0)...
Will return 0 if TV.DESC is NULL.
You can try:
with dat as (select TV.[Desc] as TipyDesc, sum(Import) as ToImp, count(*) as N, month(Date) as Mounth
from /*DATA SOURCE HERE*/ as TV
group by [Desc], month(Date))
select [TipyDesc], ToImp, N, Mounth from dat
union all
select '0', 0, 0, 0 where (select count (*) from dat)=0
That should do what you want...
If it's ok to include the "0 0 0 0" row in a result set that has data, you can use a union:
SELECT TV.Desc as TipyDesc,
sum(Import) as TotImp,
count(*) as N,
month(Date) as Mounth
...
UNION
SELECT
0,0,0,0
Depending on the database, you may need a FROM for the second SELECT. In Oracle, this would be "FROM DUAL". For MySQL, no FROM is necessary
I have query that work for me only when values in the StakeValue don't repeat.
Basically, I need to select maximum values from SI_STAKES table with their relations from two other tables grouped by internal type.
SELECT a.StakeValue, b.[StakeName], c.[ProviderName]
FROM SI_STAKES AS a
INNER JOIN SI_STAKESTYPES AS b ON a.[StakeTypeID] = b.[ID]
INNER JOIN SI_PROVIDERS AS c ON a.[ProviderID] = c.[ID] WHERE a.[EventID]=6
AND a.[StakeGroupTypeID]=1
AND a.StakeValue IN
(SELECT MAX(d.StakeValue) FROM SI_STAKES AS d
WHERE d.[EventID]=a.[EventID] AND d.[StakeGroupTypeID]=a.[StakeGroupTypeID]
GROUP BY d.[StakeTypeID])
ORDER BY b.[StakeName], a.[StakeValue] DESC
Results for example must be:
[ID] [MaxValue] [StakeTypeID] [ProviderName]
1 1,5 6 provider1
2 3,75 7 provider2
3 7,6 8 provider3
Thank you for your help
There are two problems to solve here.
1) Finding the max values per type. This will get the Max value per StakeType and make sure that we do the exercise only for the wanted events and group type.
SELECT StakeGroupTypeID, EventID, StakeTypeID, MAX(StakeValue) AS MaxStakeValue
FROM SI_STAKES
WHERE Stake.[EventID]=6
AND Stake.[StakeGroupTypeID]=1
GROUP BY StakeGroupTypeID, EventID, StakeTypeID
2) Then we need to get only one return back for that value since it may be present more then once.
Using the Max Value, we must find a unique row for each I usually do this by getting the Max ID is has the added advantage of getting me the most recent entry.
SELECT MAX(SMaxID.ID) AS ID
FROM SI_STAKES AS SMaxID
INNER JOIN (
SELECT StakeGroupTypeID, EventID, StakeTypeID, MAX(StakeValue) AS MaxStakeValue
FROM SI_STAKES
WHERE Stake.[EventID]=6
AND Stake.[StakeGroupTypeID]=1
GROUP BY StakeGroupTypeID, EventID, StakeTypeID
) AS SMaxVal ON SMaxID.StakeTypeID = SMaxVal.StakeTypeID
AND SMaxID.StakeValue = SMaxVal.MaxStakeValue
AND SMaxID.EventID = SMaxVal.EventID
AND SMaxID.StakeGroupTypeID = SMaxVal.StakeGroupTypeID
3) Now that we have the ID's of the rows that we want, we can just get that information.
SELECT Stakes.ID, Stakes.StakeValue, SType.StakeName, SProv.ProviderName
FROM SI_STAKES AS Stakes
INNER JOIN SI_STAKESTYPES AS SType ON Stake.[StakeTypeID] = SType.[ID]
INNER JOIN SI_PROVIDERS AS SProv ON Stake.[ProviderID] = SProv.[ID]
WHERE Stake.ID IN (
SELECT MAX(SMaxID.ID) AS ID
FROM SI_STAKES AS SMaxID
INNER JOIN (
SELECT StakeGroupTypeID, EventID, StakeTypeID, MAX(StakeValue) AS MaxStakeValue
FROM SI_STAKES
WHERE Stake.[EventID]=6
AND Stake.[StakeGroupTypeID]=1
GROUP BY StakeGroupTypeID, EventID, StakeTypeID
) AS SMaxVal ON SMaxID.StakeTypeID = SMaxVal.StakeTypeID
AND SMaxID.StakeValue = SMaxVal.MaxStakeValue
AND SMaxID.EventID = SMaxVal.EventID
AND SMaxID.StakeGroupTypeID = SMaxVal.StakeGroupTypeID
)
You can use the over clause since you're using T-SQL (hopefully 2005+):
select distinct
a.stakevalue,
max(a.stakevalue) over (partition by a.staketypeid) as maxvalue,
b.staketypeid,
c.providername
from
si_stakes a
inner join si_stakestypes b on
a.staketypeid = b.id
inner join si_providers c on
a.providerid = c.id
where
a.eventid = 6
and a.stakegrouptypeid = 1
Essentially, this will find the max a.stakevalue for each a.staketypeid. Using a distinct will return one and only one row. Now, if you wanted to include the min a.id along with it, you could use row_number to accomplish this:
select
s.id,
s.maxvalue,
s.staketypeid,
s.providername
from (
select
row_number() over (order by a.stakevalue desc
partition by a.staketypeid) as rownum,
a.id,
a.stakevalue as maxvalue,
b.staketypeid,
c.providername
from
si_stakes a
inner join si_stakestypes b on
a.staketypeid = b.id
inner join si_providers c on
a.providerid = c.id
where
a.eventid = 6
and a.stakegrouptypeid = 1
) s
where
s.rownum = 1