Is there any effect on Result due to column ordering in Group by clause in SQL server - sql

If i have 20 columns and want to get result based on group by clause. Is there any effect on result if I change the order of columns in SQL query.
My example is as follows :
Select
R.ClientId
,R.FirmName
,R.StrategyID
,R.SecurityType
,SUM(R.QtySent)
,SUM(R.ExecutedQty) AS ExecutedQty
,SUM(R.CrossedExecutedQty) AS CrossedExecutedQty
FROM ClientDetail m inner join ClientMaster c on
m.clordid = c.masterorderId
and m.msg_id = 43
and c.msg_id in (10,11,12,40)--Msg_Id 40 for manual trade
inner join #ResultsDaily R on c.clordid = R.clordid
GROUP BY R.TethysClientId
,R.FirmName
,R.StrategyID
,R.SecurityType

--Query 1
SELECT R.ClientId --A
,R.FirmName --B
,R.StrategyID --C
,R.SecurityType --D
,SUM(R.QtySent)
,SUM(R.ExecutedQty) AS ExecutedQty
,SUM(R.CrossedExecutedQty) AS CrossedExecutedQty
FROM ClientDetail m
JOIN ClientMaster c
ON m.clordid = c.masterorderId
AND m.msg_id = 43
AND c.msg_id in (10,11,12,40)
JOIN #ResultsDaily R on c.clordid = R.clordid
GROUP BY R.TethysClientId --1
,R.FirmName --2
,R.StrategyID --3
,R.SecurityType --4
In the above Query, 1,2,3 and 4 can be of any order. same time A,B,C and D can be also be in any order.
No column should be missed , thats all.
Parden, if i misinterpreted the Question.

Related

Selecting Rows That Have One Value but Not Another

I need a get some rows of two tables with join that shoud have one value in a column (1407) but shouldn't have other value (1403)
These is the tables and the query:
select a.job, a.date, b.group from log a inner join active_tmp b
on a.jobno=b.jobno and a.no=b.no where b.list = 'N'
AND LOGDATE = TO_CHAR(TRUNC(SYSDATE),'YYYYMMDD')
and a.job not like 'HOUSE%'
and a.job not like 'CAR%' and (errorCode=1047 and errorCode<>1403);
LOG
JOB DATE LOGDATE JOBNO NO errorCode
MAM 20220123 20220125 33 22 1047
MAM 20220123 20220125 33 22 1403
DAD 20220122 20220125 11 99 1047
MAM 20220122 20220125 33 22 0323
DAD 20220122 20220125 11 99 0444
ACTIVE_TMP
JOB JOBNO NO GROUP LIST
MAM 33 22 LAPTOP N
MAM 33 22 LAPTOP N
DAD 11 99 KEY N
But I get:
MAM,20220123,LAPTOP
DAD,20220122,KEY
I need:
DAD,20220122,KEY
Because MAM have both codes (1047 and 1043).
To rephrase, I think you mean "I want to return matching rows that have error code 1047 but for which the same values of jobno, no, list do not have a corresponding row with error code 1403"
This part is redundant:
AND (errorCode = 1047 AND errorCode <> 1403);
If you are saying errorCode must be 1047, you are also saying it is not equal to 1403.
I think you want to select some rows into some result set, then check that there's not another row that disqualifies one of the selected rows from the final result.
So,
SELECT a.job,
a.date,
b.group
FROM _log a
INNER JOIN _active_tmp b
ON a.jobno = b.jobno
AND a.no = b.no
WHERE b.list = 'N'
AND LOGDATE = TO_CHAR(CURRENT_TIMESTAMP,'YYYYMMDD')
AND a.job NOT LIKE 'HOUSE%'
AND a.job NOT LIKE 'CAR%'
AND a.errorCode = 1047
AND NOT EXISTS (SELECT 1
FROM _log c
INNER JOIN _active_tmp d
ON c.jobno = d.jobno
AND c.no = d.no
WHERE a.job = c.job
AND a.date = c.date
AND b.group = d.group
AND c.errorCode = 1403)
We select the rows that satisfy the join and have error code 1047 then subtract from that set those rows that also satisfy the join but have error code 1403. You could possibly make this more terse using CTE or a temp table, but this works too.
Note I had to change a few things to make it work in my engine (Postgres), so you may have to change a few things back to Oracle.
You need to change the error code logic. Identify what JOB values has 1403 and then exclude those values
select distinct a.job, a.date, b.[group] from LOG a inner join active_tmp b
on a.jobno=b.jobno and a.no=b.no where b.list = 'N'
AND LOGDATE = TO_CHAR(TRUNC(SYSDATE),'YYYYMMDD')
and a.job not like 'HOUSE%'
and a.job not like 'CAR%' and a.job not in (select JOB from log where errorCode in(1403));

Sql right outer join ignore all null rows

Old SQL query
SELECT
ISNULL(SUM(ColValue1), 0.00) AS Rejection
FROM
Tabel1 a, Table2 b, Table3 c
WHERE
b.col1 =* a.col2
AND c.col1 = a.col3
AND b.colx = 'xxxxxxx'
AND YEAR(TDate) = 2017
AND MONTH(TDate) = 11
GROUP BY
c.columnz
ORDER BY
c.columnZ
This returns 15 rows based on c.columnz:
Rejection
-----------
0.02897429
0.02215681
0.00000000
0.00000000
0.00000000
0.58119017
0.24542928
1.17601530
1.41633147
0.00000000
0.00000000
0.51131100
0.00000000
1.10613613
0.09033161
After I converted the query to SQL Server 2008:
SELECT
ISNULL(SUM(ColValue1), 0.00) AS Rejection
FROM
Table2 b
RIGHT OUTER JOIN
Tabel1 a ON b.col1 = a.col2
,Table3 c
WHERE
c.col1 = a.col3
AND b.colx = 'xxxxxxx'
AND YEAR(TDate) = 2017
AND MONTH(TDate) = 11
GROUP BY
c.columnz
ORDER BY
c.columnZ
The query only returns 9 rows (ignored all null rows)
Rejection
----------
0.02897429
0.02215681
0.58119017
0.24542928
1.17601530
1.41633147
0.51131100
1.10613613
0.09033161
Please help me fix the new query and get it to return all 15 rows.
All three tables and columns
SELECT
[REJ_CODE], [REJ_GROUPING], [TYPE]
FROM
[QAApr2006].[dbo].[Reject_Group];
SELECT
[REJ_RKEY], [REJECT_CODE],
[REJECT_DESCRIPTION], [REJECT_ABBRV]
FROM
[QAApr2006].[dbo].[Reject_Code];
SELECT
[PR_GRP_CODE], [PROD_CODE],
[CUSTOMER_PART_DESC], [TDATE],
[REJ_CODE], [REJ_PARTS], [REJ_M2],
[P_TYPE], [WO_Number],
[REJ_CODE_ABBRV], [REJECT_DESCRIPTION]
FROM
[QAApr2006].[dbo].[QA_Rej_Det1];
try 2
in a comment below "c. REJ_GROUPING has 15 rows and b.[Tdate]" so I upended the query as follows:
SELECT
ISNULL(SUM(REJ_M2), 0.00) AS rejection
FROM [QAApr2006].[dbo].Reject_Group c
LEFT JOIN [QAApr2006].[dbo].Reject_Code a ON c.REJ_CODE = a.REJECT_CODE
LEFT JOIN [QAApr2006].[dbo].QA_Rej_Det1 b ON a.REJ_RKEY = b.REJ_CODE
AND b.CUSTOMER_PART_DESC = '0115761002'
AND b.[Tdate] >= '20171101'
AND b.[Tdate] < '20171201'
GROUP BY
c.REJ_GROUPING
ORDER BY
c.REJ_GROUPING
It worked (although the confirming comment was added elsewhere).
original:
The alias b is used in the where clause so it is most likely to be the table we use first in the from clause so the outer joins now are left joins.
SELECT
ISNULL(SUM(REJ_M2), 0.00) AS rejection
FROM [QAApr2006].[dbo].QA_Rej_Det1 b
LEFT JOIN [QAApr2006].[dbo].Reject_Code a ON b.REJ_CODE = a.REJ_RKEY
LEFT JOIN [QAApr2006].[dbo].Reject_Group c ON a.REJECT_CODE = c.REJ_CODE
WHERE b.CUSTOMER_PART_DESC = '0115761002'
AND TDate >= '20171101'
AND TDate < '20171201'
GROUP BY
REJ_GROUPING
ORDER BY
Rej_Grouping
There is simply no good reason to use YEAR() and MONTH() to achieve an accurate date range filter, just nominate the 1st date of the month you want, and the 1st of the next month.
The other thing this query seriously suffers from is that REJ_M2,REJ_GROUPING and Tdate have no table aliases, so I really have no idea if the left joins are effective or not. Reference EVER column with the table aliases (or table names if aliases aren't supplied).
----
As a personal note I really detest aliases that indicate sequence in a query (a,b,c...) because if we need to re-sequence all of a sudden those aliases are really painful. I prefer "first letter" or "first-letter-of-each-word" as the aliases method, e.g.
SELECT
ISNULL(SUM(rc.REJ_M2), 0.00) AS rejection
FROM [QAApr2006].[dbo].QA_Rej_Det1 q
LEFT JOIN [QAApr2006].[dbo].Reject_Code rc ON q.REJ_CODE = rc.REJ_RKEY
LEFT JOIN [QAApr2006].[dbo].Reject_Group rg ON rc.REJECT_CODE = rg.REJ_CODE
WHERE q.CUSTOMER_PART_DESC = '0115761002'
AND q.TDate >= '20171101'
AND q.TDate < '20171201'
GROUP BY
q.REJ_GROUPING
ORDER BY
q.Rej_Grouping
This variant may not work because the column aliases are just guesses, & I'm not fixing that.

SQL statement merge two rows into one

In the results of my sql-statement (SQL Server 2016) I would like to combine two rows with the same value in two columns ("study_id" and "study_start") into one row and keep the row with higest value in a third cell ("Id"). If any columns (i.e. "App_id" or "Date_arrival) in the row with higest Id is NULL, then it should take the value from the row with the lowest "Id".
I get the result below:
Id study_id study_start Code Expl Desc Startmonth App_id Date_arrival Efter_op Date_begin
167262 878899 954 4.1 udd.ord Afbrudt feb 86666 21-06-2012 N 17-08-2012
180537 878899 954 1 Afsluttet Afsluttet feb NULL NULL NULL NULL
And I would like to get this result:
Id study_id study_start Code Expl Desc Startmonth App_id Date_arrival Efter_op Date_begin
180537 878899 954 1 Afsluttet Afsluttet feb 86666 21-06-2012 N 17-08-2012
My statement looks like this:
SELECT dbo.PopulationStam_V.ELEV_ID AS id,
dbo.PopulationStam_V.PERS_ID AS study_id,
dbo.STUDIESTARTER.STUDST_ID AS study_start,
dbo.Optagelse_Studiestatus.AFGANGSARSAG AS Code,
dbo.Optagelse_Studiestatus.KORT_BETEGNELSE AS Expl,
ISNULL((CAST(dbo.Optagelse_Studiestatus.Studiestatus AS varchar(20))), 'Indskrevet') AS 'Desc',
dbo.STUDIESTARTER.OPTAG_START_MANED AS Startmonth,
dbo.ANSOGNINGER.ANSOG_ID as App_id,
dbo.ANSOGNINGER.ANKOMSTDATO AS Data_arrival',
dbo.ANSOGNINGER.EFTEROPTAG AS Efter_op,
dbo.ANSOGNINGER.STATUSDATO AS Date_begin
FROM dbo.INSTITUTIONER
INNER JOIN dbo.PopulationStam_V
ON dbo.INSTITUTIONER.INST_ID = dbo.PopulationStam_V.SEMI_ID
LEFT JOIN dbo.ANSOGNINGER
ON dbo.PopulationStam_V.ELEV_ID = dbo.ANSOGNINGER.ELEV_ID
INNER JOIN dbo.STUDIESTARTER
ON dbo.PopulationStam_V.STUDST_ID_OPRINDELIG = dbo.STUDIESTARTER.STUDST_ID
INNER JOIN dbo.UDD_NAVNE_T
ON dbo.PopulationStam_V.UDDA_ID = dbo.UDD_NAVNE_T.UDD_ID
INNER JOIN dbo.UDDANNELSER
ON dbo.UDD_NAVNE_T.UDD_ID = dbo.UDDANNELSER.UDDA_ID
LEFT OUTER JOIN dbo.PERSONER
ON dbo.PopulationStam_V.PERS_ID = dbo.PERSONER.PERS_ID
LEFT OUTER JOIN dbo.POSTNR
ON dbo.PERSONER.PONR_ID = dbo.POSTNR.PONR_ID
LEFT OUTER JOIN dbo.KønAlleElevID_V
ON dbo.PopulationStam_V.ELEV_ID = dbo.KønAlleElevID_V.ELEV_ID
LEFT OUTER JOIN dbo.Optagelse_Studiestatus
ON dbo.PopulationStam_V.AFAR_ID = dbo.Optagelse_Studiestatus.AFAR_ID
LEFT OUTER JOIN dbo.frafaldsmodel_adgangsgrundlag
ON dbo.frafaldsmodel_adgangsgrundlag.ELEV_ID = dbo.PopulationStam_V.ELEV_ID
LEFT OUTER JOIN dbo.Optagelse_prioriteterUFM
ON dbo.Optagelse_prioriteterUFM.cpr = dbo.PopulationStam_V.CPR_NR
AND dbo.Optagelse_prioriteterUFM.Aar = dbo.frafaldsmodel_adgangsgrundlag.optagelsesaar
LEFT OUTER JOIN dbo.frafaldsmodel_stoettetabel_uddannelser AS fsu
ON fsu.id_uddannelse = dbo.UDDANNELSER.UDDA_ID
AND fsu.id_inst = dbo.INSTITUTIONER.INST_ID
AND fsu.uddannelse_aar = dbo.frafaldsmodel_adgangsgrundlag.optagelsesaar
WHERE dbo.STUDIESTARTER.STUDIESTARTSDATO > '2012-03-01 00:00:00.000'
AND (dbo.Optagelse_Studiestatus.AFGANGSARSAG IS NULL
OR dbo.Optagelse_Studiestatus.AFGANGSARSAG NOT LIKE '2.7.4')
AND (dbo.PopulationStam_V.INDSKRIVNINGSFORM = '1100'
OR dbo.PopulationStam_V.INDSKRIVNINGSFORM = '1700')
GROUP BY dbo.PopulationStam_V.ELEV_ID,
dbo.PopulationStam_V.PERS_ID,
dbo.STUDIESTARTER.STUDST_ID,
dbo.Optagelse_Studiestatus.AFGANGSARSAG,
dbo.Optagelse_Studiestatus.KORT_BETEGNELSE,
dbo.STUDIESTARTER.OPTAG_START_MANED,
Studiestatus,
dbo.ANSOGNINGER.ANSOG_ID,
dbo.ANSOGNINGER.ANKOMSTDATO,
dbo.ANSOGNINGER.EFTEROPTAG,
dbo.ANSOGNINGER.STATUSDATO
I really hope somebody out there can help.
Many ways, this will work:
WITH subSource AS (
/* Your query here */
)
SELECT
s1.id,
/* all other columns work like this:
COALESCE(S1.column,s2.column)
for example: */
coalesce(s1.appid,s2.appid) as appid
FROM subSource s1
INNER JOIN subSource s2
ON s1.study_id =s2.study_id
and s1.study_start = s2.study_start
AND s1.id > s2.id
/* I imagine some other clauses might be needed but maybe not */
The rest is copy paste

SQL AVG statement another table

I'm having trouble with a SQL query. The goal is to see only the certain entries on a specific date (I got this already) which have an average score below 1 in their last 5 home games.
You can see the tables here:
http://dbup2date.uni-bayreuth.de/downloads/bundesliga/Klassendiagramm_Bundesliga.pdf
I have this code so far:
SELECT
A.Spieltag, A.Datum, A.Uhrzeit, B.Name AS Heim
FROM
Spiel AS A
JOIN
Verein AS B ON A.Heim = B.V_ID AND B.Liga = 1
WHERE
Spieltag = 5
HAVING
AVG(SELECT Tore_Heim
FROM Spiel AS A
JOIN Verein AS B
WHEN A.Heim = B.V_ID) < 1
Sorry for my bad English
Thank you
Make sure you group by any =fields that you are not aggregating on when you use HAVING. And you can simplify that HAVING clause since you are already referencing those exact tables in your FROM:
SELECT
A.Spieltag, A.Datum, A.Uhrzeit, B.Name AS Heim
FROM
Spiel AS A
JOIN
Verein AS B ON A.Heim = B.V_ID AND B.Liga = 1
WHERE
Spieltag = 5
GROUP BY A.Spieltag, A.Datum, A.Uhrzeit, B.Name
HAVING
AVG(Tore_Heim) < 1

Merge results to one column

I have the following query:
SELECT a.User1 as Employee
, isnull(sum(distinct b.Page_Count),0) AS Yesterday
, isnull(sum(distinct c.Page_Count),0) AS Today
, isnull(sum(distinct d.Page_Count),0) AS Week
, e.Material_Location as '(Yesterday)'
, f.Material_Location as '(Today)'
From TaskUser AS a
LEFT JOIN PaperMaterial AS b
ON b.Assigned_To = a.User1
AND b.Date_Assigned between ('06/09/2014') AND ('06/13/2014')
LEFT JOIN PaperMaterial AS c
ON c.Assigned_To = a.User1
AND c.Date_Assigned between ('06/13/2014') AND ('06/14/2014')
LEFT JOIN PaperMaterial AS d
ON d.Assigned_To = a.User1
AND d.Date_Assigned between ('06/09/2014') AND ('06/14/2014')
LEFT JOIN PaperMaterial AS e
ON e.Assigned_To = a.User1
AND e.Date_Assigned between ('06/12/2014') AND ('06/13/2014')
LEFT JOIN PaperMaterial AS f
ON f.Assigned_To = a.User1
AND f.Date_Assigned between ('06/13/2014') AND ('06/14/2014')
GROUP BY a.User1, e.Material_Location, f.Material_Location
Order By a.User1, e.Material_Location, f.Material_Location
If multiple records were input for the same user on the same day, I am getting unique rows for the same person. I only want one row per user with the e and f results merged to the same column.
Ie: Current Output =
Amy 0 640 640 NoTask Task
Amy 0 640 640 Task2 Task
Amy 0 640 640 Task3 Task4
Amy 0 640 640 Task1 NoTask
Requested output:
Amy 0 640 640 (NoTask, Task1, Task2, Task3) (NoTask, Task, Task4)
Here's a greatly over-simplified example of using stuff combined with a correlated subquery:
SQL Fiddle
I used your output as a table, more or less:
select
name,
stuff(
(
select cast(',' as varchar(max)) + mt.one
from MyTable mt
WHERE mt.name = t1.name
order by mt.name
for xml path('')
), 1, 1, '')
from mytable t1
group by name
We're using stuff to concatenate each value for the column I creatively named ONE for each NAME. The correlated subquery allows us to relate each row coming out of that to the corresponding row coming out of the main query.