Issue with properly declaring operators Insert query SQL Server - sql-server

The query executes but it affects only 1 row which is the first found.
I did manage to get it to work as intended here is the working query:
select *
from Game.dbo.TCharacterAbility;
select t.user_id, i.*
from TCharacterAbility as i
join TCharacter as t on i.char_id = t.id
where (i.strength > '746' or
i.dexterity > '746' or
i.quickness > '746' or
i.mentality > '746' or
i.health > '746' or
i.intelligence > '746')
Here is the one I struggle with:
DEClARE #user_id int;
DEClARE #char_id int;
SELECT #char_id = id
FROM TCharacter as x
INNER JOIN tcharacterability y ON x.id = y.char_id
WHERE (y.strength > '746' OR y.dexterity > '746' OR
y.quickness > '746' OR y.mentality > '746' OR
y.health > '746' OR y.intelligence > '746')
SELECT #user_id = user_id
FROM TCharacter as x
INNER JOIN tcharacterability y ON x.id = y.char_id
WHERE (y.strength > '746' OR y.dexterity > '746' OR
y.quickness > '746' OR y.mentality > '746' OR
y.health > '746' OR y.intelligence > '746')
INSERT INTO [User].[dbo].[TDisconnect] (user_id, server_id, char_id) VALUES (#user_id, 1, #char_id)
I've tried to declare the operators the best I could, but failed miserably.
More information about the tables
t.characterability - columns:
char_id | strength | dexterity | mentality | quickness | health | intelligence |
t.character:
id (equal to char_id from characterability) | user_id | name | etc |
There's no other shared information except for id = char_id.
My goal is this query to find all the results not just the first one and insert the proper volume of matches.

varoables a scalar values and can not hold more than one so you need another approach for that
INSERT INTO [User].[dbo].[TDisconnect] (user_id,server_id,char_id)
SELECT user_id,1,id
from TCharacter as x INNER JOIN tcharacterability y on x.id =y.char_id
where (y.strength >'746' or y.dexterity>'746' or y.quickness>'746' or y.mentality>'746' or y.health>'746' or y.intelligence>'746')

Related

Remove duplicate rows from query based on value in one column

I have a table (SQL Server) where I store the run status of all of our automated test cases and I'm trying to come up with an SQL query to retrieve the status per runid, but I'm running into some problems with it.
Example of data within the table:
KRUNID | KTIME | FK_TC_ID | NOPART | STATUS | ENV
-------+----------------+------------+--------+--------+-----
4180-2 | 20190109080000 | TC0001 | 123456 | Passed | INT
4180-2 | 20190109080100 | TC0002 | 123457 | Failed | INT
4180-2 | 20190109080200 | TC0003 | 123458 | Passed | INT
4180-2 | 20190109080400 | TC0002 | 123459 | Passed | INT
Right now, I have this query (the join statements are used to display the actual test case name and business domain):
SELECT KRUNID, TD_NAME, TS_NAME, FK_TC_ID, TC_DISPLAYNAME, NOPARTENAIRE,
ENV, STATUS FROM RU_RUNSTATUS
INNER JOIN TC_TESTCASES ON K_TC_ID = FK_TC_ID
INNER JOIN TS_TCSUBDOMAINS ON K_TS_ID = FK_TS_ID
INNER JOIN TD_TCDOMAINS on K_TD_ID = FK_TD_ID
WHERE KRUNID = '418-2'
ORDER BY FK_TS_ID, K_TC_ID
The query is basic and it works fine except that I will have 2 lines for TC0002 when I only want to have the last one based on KTIME (for various reasons I don't want to filter based on STATUS).
I haven't found the right way to modify my query to get the result I want. How can I do that?
Thanks
I think this article can be respond : Get top 1 row of each group
Look of your query with limit partioned by FK_TC_ID and ordered by KTIME
;WITH cte AS
(
SELECT FK_TS_ID, KRUNID, TD_NAME, TS_NAME, FK_TC_ID , TC_DISPLAYNAME, NOPARTENAIRE,
ENV, STATUS, ROW_NUMBER() OVER (PARTITION BY FK_TC_ID ORDER BY KTIME DESC) AS rn
FROM RU_RUNSTATUS
INNER JOIN TC_TESTCASES ON K_TC_ID = FK_TC_ID
INNER JOIN TS_TCSUBDOMAINS ON K_TS_ID = FK_TS_ID
INNER JOIN TD_TCDOMAINS on K_TD_ID = FK_TD_ID
WHERE KRUNID = '418-2'
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY FK_TS_ID, K_TC_ID

SQL Server - Each GROUP BY expression must contain at least one column that is not an outer reference

I need to identify all records that have MostRecent=-1, OilWell=-1, plus are duplicate records with the same Api, and join these to get the associated CompanyName.
With the query:
SELECT
BLMAPDCONTACT.CompanyName, APD.Api, APD.ID, APD.MostRecent,
APD.Project_Nu, APD.Unit_Lease, APD.Well_Nu, APD.OilWell
FROM
APD
INNER JOIN
BLMAPDCONTACT ON APD.BLM_APD_Cont = BLMAPDCONTACT.OBJECTID
WHERE
(APD.Api IN (SELECT APD.Api
FROM APD AS Tmp
WHERE APD.MostRecent = -1 AND APD.OilWell = -1
GROUP BY APD.Api
HAVING Count(APD.Api) > 1))
ORDER BY
APD.Api DESC;
I get this error:
Each GROUP BY expression must contain at least one column that is not an outer reference.
This error appeared after I added the JOIN clause; without it, it worked.
Example desired output will match on the following records from the APD table:
APD.Api | APD.MostRecent | APD.OilWell
--------------------------------------
123 | -1 | -1
123 | -1 | -1
And not:
APD.Api | APD.MostRecent | APD.OilWell
--------------------------------------
321 | 0 | -1
321 | -1 | -1
did you try this:
SELECT BLMAPDCONTACT.CompanyName, APD.Api, APD.ID, APD.MostRecent, APD.Project_Nu, APD.Unit_Lease, APD.Well_Nu, APD.OilWell
FROM APD INNER JOIN BLMAPDCONTACT ON APD.BLM_APD_Cont = BLMAPDCONTACT.OBJECTID
WHERE (APD.Api IN
(SELECT tmp.Api
FROM APD As Tmp
WHERE tmp.MostRecent=-1 AND tmp.OilWell=-1
GROUP BY tmp.Api HAVING Count(tmp.Api)>1))
ORDER BY APD.Api DESC;
The aliases and table names are confusing me a bit. If you run the following, do you still get the same error?
SELECT b.CompanyName
, a.Api
, a.ID
, a.MostRecent
, a.Project_Nu
, a.Unit_Lease
, a.Well_Nu
, a.OilWell
FROM APD a INNER JOIN BLMAPDCONTACT b
ON a.BLM_APD_Cont = b.OBJECTID
WHERE a.Api IN (
SELECT tmp.Api
FROM APD As Tmp
WHERE tmp.MostRecent = -1 AND tmp.OilWell = -1
GROUP BY tmp.Api
HAVING Count(tmp.Api) > 1
)
ORDER BY a.Api DESC;
Also, just double check that I've translated tables to aliases correctly.

T-SQL AVG of multiple columns in a row

I'm trying to select the average sales per person per territory out of the AdventureWorks database.
Since this is aggregating multiple columns in a row instead of multiple rows in a column, it seems like I'd need a sub-query, temp table, maybe a CTE, but I'm not sure how to identify which direction to take or how to write it.
Desired result:
| SalesTerritory | SalesPeople | 2011 | 2012 | 2013 | 2014 | AvgSales
+----------------+-------------+--------+---------+---------+---------+----------
| Australia | 1 | NULL | NULL | 184105 | 1237705 | [avg]
| Canada | 2 | 115360 | 3426082 | 2568323 | etc... | [avg]
Code:
SELECT
pvt.SalesTerritory,
COUNT(pvt.SalesPersonID) AS SalesPeople,
SUM(pvt.[2011]),
SUM(pvt.[2012]),
SUM(pvt.[2013]),
SUM(pvt.[2014])
--What's the best way to AVG the sales by year by sales person for each territory here?
FROM
(SELECT
st.[Name] AS [SalesTerritory],
soh.[SalesPersonID],
soh.[SubTotal],
YEAR(DATEADD(m, 6, soh.[OrderDate])) AS [FiscalYear]
FROM
[Sales].[SalesPerson] sp
INNER JOIN
[Sales].[SalesOrderHeader] soh ON sp.[BusinessEntityID] = soh.[SalesPersonID]
INNER JOIN
[Sales].[SalesTerritory] st ON sp.[TerritoryID] = st.[TerritoryID]
INNER JOIN
[HumanResources].[Employee] e ON soh.[SalesPersonID] = e.[BusinessEntityID]
INNER JOIN
[Person].[Person] p ON p.[BusinessEntityID] = sp.[BusinessEntityID]) AS soh
PIVOT
(SUM([SubTotal]) FOR [FiscalYear] IN ([2011], [2012], [2013], [2014])) AS pvt
GROUP BY
pvt.SalesTerritory
You have several options:
1) Use cross apply. Query would look like:
select
*
from
(
--put your query here
) t
cross apply (select AvgSales = avg(v) from (values ([2011]), ([2012]), ([2013]), ([2014])) q(v)) q
2) Count average by yourself
SELECT
pvt.SalesTerritory,
COUNT(pvt.SalesPersonID) AS SalesPeople,
SUM(pvt.[2011]),
SUM(pvt.[2012]),
SUM(pvt.[2013]),
SUM(pvt.[2014]),
ISNULL(SUM(pvt.[2011]), 0) + ISNULL(SUM(pvt.[2012]), 0)
+ ISNULL(SUM(pvt.[2013]), 0) + ISNULL(SUM(pvt.[2014]), 0)
/ CASE WHEN SUM(pvt.[2011]) > 0 THEN 1 ELSE 0 END
+ CASE WHEN SUM(pvt.[2012]) > 0 THEN 1 ELSE 0 END
+ CASE WHEN SUM(pvt.[2013]) > 0 THEN 1 ELSE 0 END
+ CASE WHEN SUM(pvt.[2014]) > 0 THEN 1 ELSE 0 END
FROM
...
GROUP BY
pvt.SalesTerritory
As I understand your question, you need the average of the yearly sales per salesperson, for each territory. Uzi's answer provides the average of the yearly sales for all salespersons together, for each territory. You could divide that result by the number of salespersons, or use a query like this:
SELECT pvt.SalesTerritory, COUNT(pvt.SalesPersonID) AS SalesPeople,
SUM(pvt.[2011]) AS [2011], SUM(pvt.[2012]) AS [2012],
SUM(pvt.[2013]) AS [2013], SUM(pvt.[2014]) AS [2014],
AVG(pvt.AvgSubTotal) AS AvgSubTotal
FROM (
SELECT y.SalesTerritory, y.SalesPersonID, y.FiscalYear, y.SubTotal,
AVG(y.SubTotal) OVER (PARTITION BY y.SalesTerritory) AS AvgSubTotal
FROM (
SELECT x.SalesTerritory, x.SalesPersonID, x.FiscalYear, SUM(x.SubTotal) AS SubTotal
FROM (
SELECT st.Name AS SalesTerritory, soh.SalesPersonID, soh.SubTotal,
YEAR(DATEADD(m, 6, soh.OrderDate)) AS FiscalYear
FROM Sales.SalesPerson sp
INNER JOIN Sales.SalesOrderHeader soh ON sp.BusinessEntityID = soh.SalesPersonID
INNER JOIN Sales.SalesTerritory st ON sp.TerritoryID = st.TerritoryID
INNER JOIN HumanResources.Employee e ON soh.SalesPersonID = e.BusinessEntityID
INNER JOIN Person.Person p ON p.BusinessEntityID = sp.BusinessEntityID
) x
GROUP BY x.SalesTerritory, x.SalesPersonID, x.FiscalYear
) y
) AS soh
PIVOT (SUM(SubTotal) FOR FiscalYear IN ([2011], [2012], [2013], [2014])) AS pvt
GROUP BY pvt.SalesTerritory;
The result is different for the Northwest territory, but I'm not sure which result you want.

EF6 - Generating unneeded nested queries

I have the following tables:
MAIN_TBL:
Col1 | Col2 | Col3
------------------
A | B | C
D | E | F
And:
REF_TBL:
Ref1 | Ref2 | Ref3
------------------
A | G1 | Foo
D | G1 | Bar
Q | G2 | Xyz
I wish to write the following SQL query:
SELECT M.Col1
FROM MAIN_TBL M
LEFT JOIN REF_TBL R
ON R.Ref1 = M.Col1
AND R.Ref2 = 'G1'
WHERE M.Col3 = 'C'
I wrote the following LINQ query:
from main in dbContext.MAIN_TBL
join refr in dbContext.REF_TBL
on "G1" equals refr.Ref2
into refrLookup
from refr in refrLookup.DefaultIfEmpty()
where main.Col1 == refr.Col1
select main.Col1
And the generated SQL was:
SELECT
[MAIN_TBL].[Col1]
FROM (SELECT
[MAIN_TBL].[Col1] AS [Col1],
[MAIN_TBL].[Col2] AS [Col2],
[MAIN_TBL].[Col3] AS [Col3]
FROM [MAIN_TBL]) AS [Extent1]
INNER JOIN (SELECT
[REF_TBL].[Ref1] AS [Ref1],
[REF_TBL].[Ref2] AS [Ref2],
[REF_TBL].[Ref3] AS [Ref3]
FROM [REF_TBL]) AS [Extent2] ON [Extent1].[Col1] = [Extent2].[Ref1]
WHERE ('G1' = [Extent2].[DESCRIPTION]) AND ([Extent2].[Ref1] IS NOT NULL) AND CAST( [Extent1].[Col3] AS VARCHAR) = 'C') ...
Looks like it is nesting a query within another query, while I just want it to pull from the table. What am I doing wrong?
I may be wrong, but it looks like you don't do the same in linq query and sql query, especially on your left joining clause.
I would go for this, if you want something similar to your sql query.
from main in dbContext.MAIN_TBL.Where(x => x.Col3 == "C")
join refr in dbContext.REF_TBL
on new{n = "G1", c = main.Col1} equals new{n = refr.Ref2, c = refr.Col1}
into refrLookup
from r2 in refrLookup.DefaultIfEmpty()
select main.Col1
By the way, it doesn't make much sense to left join on a table which is not present in the select clause : you will just get multiple identical Col1 if there's more than one related item in the left joined table...

referencing three columns to same column in another table in sql server 2000

I have a question on SQL Server 2000, i need to get an report from database. I have database called Automation where it contains set of tables to handle the queries of ticketing process of our application.
I need to extract a report from database that should contain ticket number and user information like who has entered, received, edited , reviewed that ticket.
I need these fields from the database
Ticketnumber
billnumber
companyname
enteredby(username)
entereddate
recievedby(username)
recieveddate
editedby(Employeename)
editeddate
reviewedby(ReviewerName)
revieweddate
postedby(Managername)
posteddate
I have three tables
1> VPP_VendorBilldetails
BillentryID | ticketnumber | billnumber | VENDORNAME,BILLNUMBER,COSTCENTERNAME,BILLAMOUNT,TICKETDATE,BILLDATE | companyID(not companyname) | billdate | Enteredby(userid)| entereddate | recievedby(userid) | recieveddate | editedby(userid) | editeddate | reviewedby(userid) | revieweddate | postedby(userid) | posteddate
2> Users
UserID | employeeID | employeename |loginID| Password | usertype | status
3> VPP_ClientCompanyDetails :
companyid | companyname | companyaddress | status
I have written this query, but I am getting same employee name for all three categories :
SELECT CLIENTCOMPANYNAME, TICKETNUMBER,VENDORNAME,BILLNUMBER,COSTCENTERNAME,BILLAMOUNT,TICKETDATE,BILLDATE,
RECIEVEDDATE,EMPLOYEENAME AS EXECUTIVENAME,
VPP_VENDORBILLDETAILS.MODIFIEDDATE,
EMPLOYEENAME AS REVIEWERNAME,EMPLOYEENAME AS POSTEDBY,POSTEDDATE,ERRORCODE,
IMPACTCODE,ROOTCAUSE,REVIEWERREMARKS
FROM
VPP_VENDORBILLDETAILS
INNER JOIN
VPP_CLIENTCOMPANYDETAILS
ON VPP_VENDORBILLDETAILS.BILLENTEREDCOMPANYID = VPP_CLIENTCOMPANYDETAILS.CLIENTCOMPANYID
INNER JOIN USERS
ON VPP_VENDORBILLDETAILS.MODIFIEDBY = USERS.USERID
WHERE CONVERT(VARCHAR(12),CONVERT(DATETIME,POSTEDDATE,103),101)
BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-7,100),101)
AND CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-1,100),101)
AND VPP_CLIENTCOMPANYDETAILS.STATUS = 1 AND VPP_VENDORBILLDETAILS.STATUS = 1 AND USERS.STATUS = 1 AND ERRORCODE IS NOT NULL AND TALLYID IS NOT NULL
ORDER BY CLIENTCOMPANYNAME ASC
Please check it and help me on this
Please help me to extract the report the above said tables..
Try this :
SELECT CLIENTCOMPANYNAME, TICKETNUMBER,VENDORNAME,BILLNUMBER,COSTCENTERNAME,BILLAMOUNT,TICKETDATE,BILLDATE,
RECIEVEDDATE,U1.EMPLOYEENAME AS EXECUTIVENAME,
VPP_VENDORBILLDETAILS.MODIFIEDDATE,
U2.EMPLOYEENAME AS REVIEWERNAME,U3.EMPLOYEENAME AS POSTEDBY,POSTEDDATE,ERRORCODE,
IMPACTCODE,ROOTCAUSE,REVIEWERREMARKS
FROM
VPP_VENDORBILLDETAILS
INNER JOIN
VPP_CLIENTCOMPANYDETAILS
ON VPP_VENDORBILLDETAILS.BILLENTEREDCOMPANYID = VPP_CLIENTCOMPANYDETAILS.CLIENTCOMPANYID
INNER JOIN USERS U1
ON VPP_VENDORBILLDETAILS.recievedby = U1.USERID
INNER JOIN USERS U2
ON VPP_VENDORBILLDETAILS.MODIFIEDBY = U2.USERID
INNER JOIN USERS U3
ON VPP_VENDORBILLDETAILS.postedby = U3.USERID
WHERE CONVERT(VARCHAR(12),CONVERT(DATETIME,POSTEDDATE,103),101)
BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-7,100),101)
AND CONVERT(DATETIME,CONVERT(VARCHAR(12),getdate()-1,100),101)
AND VPP_CLIENTCOMPANYDETAILS.STATUS = 1 AND VPP_VENDORBILLDETAILS.STATUS = 1 AND USERS.STATUS = 1 AND ERRORCODE IS NOT NULL AND TALLYID IS NOT NULL
ORDER BY CLIENTCOMPANYNAME ASC

Resources