I have the following table structure also I have mention my expected output please help me with query as I don't know much about SQL query
Query :
SELECT * FROM(
SELECT ESIDispensary,ESILocation,test,Category, COUNT(*) AS [Total Count]
FROM
(SELECT category,ESILOCATION,ESIDISPENSARY,TEST
FROM(SELECT id,CompanyId,FName,Code,category,ESILOCATION,ESIDISPENSARY
FROM dbo.[EmployeeDetail] e WHERE e.CompanyId = 1 AND Category in (1,2)) a
LEFT JOIN
(SELECT *
from
(SELECT EmployeeId, CustomeFieldName,FieldValue
FROM dbo.[CustomeFieldDetail] C
JOIN dbo.[EmployeeDetail] e ON e.id = c.employeeid AND e.CompanyId = c.companyid
WHERE e.CompanyId = 1 AND Category IN (1,2)) SRC
PIVOT
(MAX(FieldValue) FOR CustomeFieldName IN([TEST]))
piv)
b ON a.Id = b.EmployeeId
) AS a
GROUP BY ESIDispensary ,ESILocation,test,Category) x
Table generated using above query
ESIDispensary ESILocation test Category Count
12 11 NULL 1 NULL
12 13 30 1 1
14 13 29 2 2
Table 1 : ESI
Id CompanyId FieldName ComboValue
11 1 ESILOCATION mumbai
12 1 ESIDISPENSARY mumbai
13 1 ESILOCATION pune
14 1 ESIDISPENSARY pune
29 1 TEST HDFC
30 1 TEST ICICI
Table 2 : Category
id CategoryName
1 staff
2 manager
Problem is i want to replace IDs with respected values also can i change above query to get expected result
Expected Summary Output :
ESIDispensary ESILocation test staff manager
mumbai mumbai NULL 1 NULL
mumbai pune ICICI 1 1
pune pune HDFC NULL 2
Is this is what you want:
SELECT (SELECT ComboValue FROM ESI WHERE ID = ESIDispensary) AS ESIDispensary,
SELECT ComboValue FROM ESI WHERE ID = ESILocation) AS ESILocation,
SELECT ComboValue FROM ESI WHERE ID = test) AS test,
Category, [Total Count]
FROM
(
SELECT ESIDispensary,ESILocation,test,Category, COUNT(*) AS [Total Count]
FROM
(SELECT category,ESILOCATION,ESIDISPENSARY,TEST
FROM(SELECT id,CompanyId,FName,Code,category,ESILOCATION,ESIDISPENSARY
FROM dbo.[EmployeeDetail] e WHERE e.CompanyId = 1 AND Category in (1,2)) a
LEFT JOIN
(SELECT *
from
(SELECT EmployeeId, CustomeFieldName,FieldValue
FROM dbo.[CustomeFieldDetail] C
JOIN dbo.[EmployeeDetail] e ON e.id = c.employeeid AND e.CompanyId = c.companyid
WHERE e.CompanyId = 1 AND Category IN (1,2)) SRC
PIVOT
(MAX(FieldValue) FOR CustomeFieldName IN([TEST]))
piv)
b ON a.Id = b.EmployeeId
) AS a
GROUP BY ESIDispensary, ESILocation, test, Category) x
Related
I want to select the 7th person (Pierre Gasly (for example)) Score list Season F1, so I can return number 7 in my C# application.
SELECT CONCAT(strVoorNaam, strTussenVoegsel, ' ', strAchterNaam) AS Naam, SUM(CAST(tblPunten.strScore AS INT)) AS score
FROM tblPunten
JOIN tblPuntenCoureur ON tblPuntenCoureur.PuntenID = tblPunten.ID
JOIN tblPersoon ON tblPersoon.ID = tblPuntenCoureur.PersoonID
JOIN tblSeizoen ON tblSeizoen.ID = tblPuntenCoureur.SeizoenID
WHERE tblPunten.ID != 12 AND tblPunten.ID != 13 AND tblPunten.ID != 14 AND tblPunten.ID != 15
AND tblPunten.ID != 16 AND tblPunten.ID != 17 AND tblPunten.ID != 18 AND tblPunten.ID != 19 AND tblSeizoen.intJaartal = 2019
GROUP BY CONCAT(strVoorNaam, strTussenVoegsel, ' ', strAchterNaam), tblPersoon.strAchterNaam
ORDER BY score DESC
Use a row limiting clause:
select
concat(strvoornaam, strtussenvoegsel, ' ', strachternaam) as naam,
sum(cast(pu.strscore as int)) as score
from tblpunten pu
join tblpuntencoureur pc on pc.puntenid = pu.id
join tblpersoon pe on pe.id = pc.persoonid
join tblseizoen se on se.id = pc.seizoenid
where pu.id not between 12 and 19 and se.intjaartal = 2019
group by strvoornaam, strtussenvoegsel, strachternaam, pe.strachternaam
order by score desc
offset 6 rows fetch next 1 row only
This gives you the seventh row in the resultset.
Side notes:
table aliases help keeping the query concise and easier to write
you should be qualifying all columns that come into play in the query
On the other hand, if you are trying to get the rank of a specific person, then that's different. You can use rank() instead:
select *
from (
select
concat(strvoornaam, strtussenvoegsel, ' ', strachternaam) as naam,
sum(cast(pu.strscore as int)) as score,
rank() over(order by sum(cast(pu.strscore as int)) desc) rn
from tblpunten pu
join tblpuntencoureur pc on pc.puntenid = pu.id
join tblpersoon pe on pe.id = pc.persoonid
join tblseizoen se on se.id = pc.seizoenid
where pu.id not between 12 and 19 and se.intjaartal = 2019
group by strvoornaam, strtussenvoegsel, strachternaam, pe.strachternaam
) t
where naam = 'Pierre Gasly'
I am working on a query to get monthly attendance totals by department. i.e it will show present employees in each department based on attendance logs table where check_type = 'C-IN'
Table 1: checkin_out_log
Columns: emp_id, check_time, check_type (C-IN, C-OUT)
Table 2: department
Table 3: employee
Expected output is
Department | Total Staff | Date 1 | Date 2 | Date 3|......
finance | 60 | 50 | 55 | 48 |.....
Here is my query which is currently returning me total staff in each department,
SELECT
*
FROM
(SELECT
d.id, d.name AS Department, T.DateToCheck,
COUNT(e.id) AS staff
FROM
employee e
CROSS JOIN
(SELECT
CAST(DATEADD(DAY, number, #DateFrom) AS DATE)
FROM
master..spt_values
WHERE
type = 'P'
AND DATEADD(DAY, number, #DateFrom) <= #DateTo ) T (DateToCheck)
LEFT JOIN
department d ON d.id = e.department
WHERE
d.id = 7
GROUP BY
d.id, d.name, T.DateToCheck) T
PIVOT
(MAX(staff)
FOR DateToCheck IN ([2018-09-01],[2018-09-02],[2018-09-03],[2018-09-04],[2018-09-05],[2018-09-06],[2018-09-07],[2018-09-08],[2018-09-09],[2018-09-10],
[2018-09-11],[2018-09-12],[2018-09-13],[2018-09-14],[2018-09-15],[2018-09-16],[2018-09-17],[2018-09-18],[2018-09-19],[2018-09-20],[2018-09-21],[2018-09-22],[2018-09-23],
[2018-09-24],[2018-09-25],[2018-09-26],[2018-09-27],[2018-09-28],[2018-09-29],[2018-09-30])) P
;
Been working on this SQL dilemma for a while now. The part of the table looks like the following.
It's a many-to-many table relationship where one claim can have many notes. So, one example would be the following:
------------------------------------------
| ClaimID | NoteID | Note |
------------------------------------------
| 2387 | 1 | Test 1 |
| 2387 | 2 | Test 2 |
| 2387 | 3 | Test 3 |
| 2532 | 4 | Something 1 |
| 2539 | 5 | abcd |
| 2539 | 6 | jklm |
------------------------------------------
You get the idea.
So, when I run the query I want the result in such a way that it should show me the number of note counts from 1 to 10. If the count exist, then it should show me the count, otherwise 0. An example of what it would look like in the real-world scenario is the following.
[{
"numOfNotes":1,
"count":5916
},{
"numOfNotes":2,
"count":1846
},{
"numOfNotes":3,
"count":639
},{
"numOfNotes":4,
"count":226
},{
"numOfNotes":5,
"count":94
},{
"numOfNotes":6,
"count":50
},{
"numOfNotes":7,
"count":10
},{
"numOfNotes":8,
"count":2
},{
"numOfNotes":9,
"count":2
},{
"numOfNotes":11,
"count":2
}]
That's the query return from the database that I retrieved using C# and linq. Here's the code for that.
if (type == "e" || type == "p")
{
//sub query to retrieve notes
var subquery = from f in db.DBFileInfo
join c in db.Claims on f.FileID equals c.FileID into cl
from gp1 in cl.DefaultIfEmpty()
join n in db.Notes on gp1.ClaimID equals n.ClaimID into nt
from gp2 in nt.DefaultIfEmpty()
where f.ReportDate.Month == month && f.ReportDate.Year == year
group gp2 by gp2.ClaimID into g
select new
{
Key = g.Key,
Count = g.Count()
};
//query to grop by notes count. Notes count is consider contact per claim
var count = (from c in db.Claims
join s in subquery on c.ClaimID equals s.Key
where c.RecordType == type &&
(c.Username != "RxService")
&& (c.HIC3 != "J3A" && c.HIC3 != "J3C" && c.HIC3 != "H7N")
group s by s.Count into g
orderby g.Key
select new
{
NumOfNotes = g.Key,
count = g.Count()
}).Take(10);
}
If you notice in the result, there are numOfNotes from 1 - 11 but 10 is missing. That's because there aren't any claimID that has 10 notes. So, in this case, I still want SQL to return "numOfNotes": 10, "count": 0. And if you notice, I only asked for 10 results (Take(10)), because there can be more than 10 such notes per claim which we are not interested.
And in some cases, there aren't more than 5 notes per claimID for the given time period. In one instance, the result from SQL only goes up to 6. But I still want the result upto 10 whether it exists or not. Is it possible?
In case if you're interested: Here's my SQL statement
SELECT
count(C.ClaimID) as count, N.NotesPerClaim
FROM
ClaimsTable C
INNER JOIN
(SELECT
claimid, count(note) as NotesPerClaim
FROM
NotesTable
GROUP BY
ClaimID) as N ON N.ClaimID = C.ClaimID
WHERE
RecordType = 'e' AND
(Username <> 'RxService') AND
(HIC3 <> 'J3A' AND HIC3 <> 'J3C' AND HIC3 <> 'H7N')
GROUP BY
N.NotesPerClaim
ORDER BY
N.NotesPerClaim;
You seem to want a numbers table. Here is one method:
WITH nums as (
SELECT 1 as n
UNION ALL
SELECT n + 1
FROM nums
WHERE n < 10
),
t as (
SELECT count(C.ClaimID) as NumClaims, N.NotesPerClaim
FROM ClaimsTable C JOIN
(SELECT claimid, count(note) as NotesPerClaim
FROM NotesTable
GROUP BY ClaimID
) N
ON N.ClaimID = C.ClaimID
WHERE c.RecordType = 'e' AND
c.Username <> 'RxService' AND
c.HIC3 NOT IN ('J3A', 'J3C', 'H7N')
GROUP BY N.NotesPerClaim
)
SELECT nums.n as NotesPerClaim, t.NumClaims
FROM nums LEFT JOIN
t
ON nums.n = t.NotesPerClaim
ORDER BY NotesPerClaim;
Use LEFT JOIN instead of INNER JOIN
Also is better use HIC3 NOT IN ('J3A', 'J3C', 'H7N')
SELECT count(C.ClaimID) AS count
, N.NotesPerClaim
FROM ClaimsTable C
LEFT JOIN (
SELECT claimid
, count(note) AS NotesPerClaim
FROM NotesTable
GROUP BY ClaimID
) AS N ON N.ClaimID = C.ClaimID
WHERE RecordType = 'e'
AND (Username <> 'RxService')
AND HIC3 NOT IN ('J3A', 'J3C', 'H7N')
GROUP BY N.NotesPerClaim
ORDER BY N.NotesPerClaim;
LEFT JOIN on the notes table, and check for ISNULL condition. In the case of NULL from notes, return 0.
Here is a SQL Fiddle demo of the concept.
Your code should be:
`SELECT count(C.ClaimID) as count, ISNULL(N.NotesPerClaim,0) as NotesPerClaim
FROM ClaimsTable C
LEFT OUTER JOIN
(SELECT claimid, count(note) as NotesPerClaim from NotesTable
GROUP BY ClaimID) as N
ON N.ClaimID = C.ClaimID
WHERE RecordType = 'e' AND
(Username <> 'RxService') AND (HIC3 NOT IN ('J3A','J3C','H7N'))
GROUP BY ISNULL(N.NotesPerClaim,0)
ORDER BY N.NotesPerClaim;`
I have the following data in a SQL Table:
I want to find 3 Consecutive data by No and group with ID. Result are
How to write query.please help.
Here is query which select only rows where actually 3 consecutive rows are:
SELECT a.*
FROM
TABLE as a
inner join
TABLE as b on (a.no+1=b.no and a.id=b.id)
inner join
TABLE as c on (a.no+2=c.no and a.id=c.id)
order by a.id, a.no
for your data it will provide:
4 a1 4
5 a1 3
1 a2 2
2 a2 4
3 a3 2
4 a3 3
rows (6,a1,1), (3,a2,5) and (5,a3,4) are not selected, as there are no (8,a1) (5,a2) and (7,a3)
DECLARE #temp TABLE (NO int,ID VARCHAR(2),QTY int)
INSERT INTO #temp
SELECT 1,'A1',5 UNION ALL
SELECT 4,'A1',4 UNION ALL
SELECT 5,'A1',3 UNION ALL
SELECT 6,'A1',1 UNION ALL
SELECT 7,'A1',0 UNION ALL
SELECT 9,'A1',5 UNION ALL
SELECT 12,'A1',3 UNION ALL
SELECT 1,'A2',2 UNION ALL
SELECT 2,'A2',4 UNION ALL
SELECT 3,'A2',5 UNION ALL
SELECT 4,'A2',1 UNION ALL
SELECT 7,'A2',4 UNION ALL
SELECT 9,'A2',5 UNION ALL
SELECT 1,'A3',0 UNION ALL
SELECT 3,'A3',2 UNION ALL
SELECT 4,'A3',3 UNION ALL
SELECT 5,'A3',4 UNION ALL
SELECT 6,'A3',2;
WITH tmpa AS
(
SELECT *
, NO - ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS grp
FROM #temp
)
, tmpb AS
(
SELECT *
, COUNT(*) OVER(PARTITION BY ID,grp) AS grpcount
FROM tmpa
)
SELECT NO,ID,QTY FROM tmpb WHERE grpcount>1;
Result are
4 A1 4
5 A1 3
6 A1 1
7 A1 0
1 A2 2
2 A2 4
3 A2 5
4 A2 1
3 A3 2
4 A3 3
5 A3 4
6 A3 2
I found this query from this link.
Find “n” consecutive free numbers from table
http://sqlfiddle.com/#!1/a2633/2
Answer Credit by
I have the following tables:
*sistema_documentos*
[id], [caminho], [idDocType](FK -> sistema_DocType.id)
*sistema_Indexacao*
[id] ,[idDocumento](FK -> sistema_documentos.id) ,[idIndice](FK ->
sistema_Indexes) ,[valor]
*sistema_DocType*
[id], [tipoNome](FK -> sistema_DocType.id)
*sistema_DocType_Index*
[id],[idName],[mask],[idTipo](FK -> sistema_DocType.id),[tamanho]
From this query:
select distinct a.id, b.idIndice, b.valor from tgpwebged.dbo.sistema_Documentos as a
join tgpwebged.dbo.sistema_Indexacao as b on a.id = b.idDocumento
join tgpwebged.dbo.sistema_DocType as c on a.idDocType = c.id
join tgpwebged.dbo.sistema_DocType_Index as d on c.id = d.docTypeId
where d.docTypeId = 40
and (b.idIndice = 11 AND b.valor = '11111111' OR b.idIndice = 12 AND b.valor = '22222' )
I get the following result
id idIndice valor
13 11 11111111
13 12 22222
14 11 11111111
14 12 22222
16 12 22222
As you can see, I want all ids with idIndice 11 with value 11111111 and 12 with value 22222
Id 16 has id 12 with value 22222 authough it does not have id 11 with value 11111111 so I don´t want it to be shown.
How can I update my query to obtain the result I want. Hope my question is clear. If it is not just ask and I edit my post. Thanks
I would suggest something like this:
WITH TempTable AS
(
select distinct a.id, b.idIndice, b.valor
from tgpwebged.dbo.sistema_Documentos as a
join tgpwebged.dbo.sistema_Indexacao as b on a.id = b.idDocumento
join tgpwebged.dbo.sistema_DocType as c on a.idDocType = c.id
join tgpwebged.dbo.sistema_DocType_Index as d on c.id = d.docTypeId
where d.docTypeId = 40
and (b.idIndice = 11 AND b.valor = '11111111' OR b.idIndice = 12 AND b.valor = '22222' )
)
SELECT *
FROM TempTable t1
WHERE (select count(*)
from TempTable t2
where t1.id = t2.id AND t1.valor != t2.valor) = 1
So... get all the results from your first query where there is at least one result from the table that matches on id, but does not match on valor. (This assumes you could have duplicate rows with the same valor, but you wouldn't want that.)
Try something like this. I took out the tables that didn't have direct bearing on the query, although I named them similarly, and I created a simple schema to replicate the problem. I hope this is clear, and that the connection back to your original query is likewise clear.
CREATE TABLE Documentos (ID INT, document varchar(12))
create table Indexacao (AID INT, indice int, valor varchar(12))
insert Documentos(id, document)
values (1, 'test1'),
(2, 'test2'),
(3, 'test3')
insert Indexacao (aid, indice, valor)
values (1, 11, '11111111'),
(1, 12, '22222'),
(2, 12, '22222')
The important part of the code is the INTERSECT - it returns only rows that are in both sets. In my experience this operator is usually more efficient than anything containing an OR. In the query below, we are getting only those Indexacao rows whose idDocumentos are in the INTERSECT of the two sets of conditions.
SELECT Ind.*
FROM Indexacao Ind
JOIN (
SELECT D.ID
FROM Documentos D
JOIN Indexacao I
ON D.ID = I.AID
WHERE I.Indice = 11 AND I.valor = '11111111'
INTERSECT
SELECT D.ID
FROM Documentos D
JOIN Indexacao I
ON D.ID = I.AID
WHERE I.Indice = 12 AND I.valor = '22222'
)Doc (ID)
ON Doc.ID = Ind.AID
This assumes that you don't have duplicate Indice, Valor rows for a single idDocumento - if you do, you will need to add a DISTINCT.