How to merge a select statement with a calculated value as new columns? [duplicate] - sql-server

This question already has answers here:
How to merge a select statement with a new dynamic values as columns?
(4 answers)
Closed 9 years ago.
In my sql server code, I have this select statement
select distinct
a.HireLastName,
a.HireFirstName,
a.HireID,
a.Position_ID,
a.BarNumber,
a.Archived,
a.DateArchived,
b.Position_Name
from NewHire a
join Position b on a.Position_ID = b.Position_ID
join WorkPeriod c on a.hireID = c.HireID
where a.Archived = 0 and c.InquiryID is not null
order by a.HireID DESC, a.HireLastName, a.HireFirstName
And I want to add a new column to it. However this column is not a column from a table, its just used to store a float from a calculation I make from existing columns.
The number I get is calculated like this:
#acc is the a.HireID from the above select statement.
CAST((select COUNT(*) from Hire_Response WHERE HireID = #acc AND (HireResponse = 0 OR HireResponse = 1)) as FLOAT) /
CAST((select COUNT(*) from Hire_Response WHERE HireID = #acc) as FLOAT)
How can I do this?
Thanks.

You can use the code that GBN did for you on your other question as a sub-query
select distinct
a.HireLastName,
a.HireFirstName,
a.HireID,
a.Position_ID,
a.BarNumber,
a.Archived,
a.DateArchived,
b.Position_Name,
d.percentage
from NewHire a
inner join Position b on a.Position_ID = b.Position_ID
inner join WorkPeriod c on a.hireID = c.HireID
left join (select NH.HireID, ISNULL(1E0 * COUNT(CASE WHEN HireResponse IN (0,1) THEN HR.HireID END) / NULLIF(COUNT(HR.HireID), 0) , 0) AS percentage
from NewHire NH LEFT JOIN Hire_Response HR ON NH.HireID = HR.HireID
group by NH.HireID) d
ON a.HireID = d.HireID
where a.Archived = 0 and c.InquiryID is not null
order by a.HireID DESC, a.HireLastName, a.HireFirstName
... this will add the column percentage to your current query. This could probably be improved, but it should give you a god idea of how you can bring the results of your questions together.

Related

Filtering down SQL To one value? [duplicate]

This question already has answers here:
Get top 1 row of each group
(19 answers)
Closed 1 year ago.
I'm writing a query for SAP B1,using Microsoft SQL Server Management Studio 17.
I am wanting to return the "MIN" DocDate, but show the field "ShipDate" alongside it, with only one result...
SELECT T0.ItemCode,
T3.ShipDate AS 'Next Date',
MIN(T3.DocDate) AS 'OrderDate'
FROM OITM T0
LEFT OUTER JOIN POR1 T3 ON T0.ItemCode = T3.ItemCode
WHERE T3.LineStatus = 'O' AND T3.ShipDate > GETDATE()
Group By T0.Itemcode, T3.ShipDate
This returns the following results;
ItemCode
ShipDate
OrderDate
VT3021026
2021-05-14
2021-05-04
VT3021026
2021-06-01
2021-05-10
This is an example of what one single item is returning, however I want to return only one value for each item. Almost like a "TOP 1" for each individual item. (obviously top 1 won't work in the overall select clause because it will be required to produce a list of multiple items)
If I understand you correctly, then this code will solve the problem.
DECLARE #date datetime2 = GETDATE();
WITH T(ItemCode, OrderDate) AS
(
SELECT
T0.ItemCode,
MIN(T3.DocDate) AS 'OrderDate'
FROM OITM T0
LEFT JOIN POR1 T3
ON T0.ItemCode = T3.ItemCode
WHERE T3.LineStatus = 'O'
AND T3.ShipDate > #date
GROUP BY T0.Itemcode, T3.ShipDate
)
SELECT T.ItemCode,
T4.ShipDate AS 'Next Date',
T.OrderDate
FROM T
LEFT JOIN POR1 T4
ON T.[OrderDate] = T4.DocDate
AND T.ItemCode = t4.ItemCode;

SQL Server ISNULL not working in multi table selection

I'm very new to SQL server and I'm trying to get the maximum price of an item based on the update of table and if is null to replace the null able value with zero.
Here is what I did:
DECLARE #itemid BIGINT
SELECT
(SELECT ISNULL(MAX(ITEM_SUPPLIER_PRICE.Price), 0.00)
FROM ITEM_SUPPLIER_PRICE
WHERE (ITEM_SUPPLIER_PRICE.item_id = 7)) AS price,
itemunits.unit_id,
itemunits.unit_name
FROM
ITEM_SUPPLIER_PRICE
INNER JOIN
Items ON ITEM_SUPPLIER_PRICE.item_id = Items.Item_id
INNER JOIN
itemunits ON Items.Item_unit_id = itemunits.unit_id
WHERE
(Items.Item_id = 7)
GROUP BY
itemunits.unit_id, itemunits.unit_name,
ITEM_SUPPLIER_PRICE.update_date
ORDER BY
ITEM_SUPPLIER_PRICE.update_date DESC;
I think you're just looking for the max price in the group. Since prices probably can't be negative, the second option below should be equivalent but I throw it in just in case the problem is there.
SELECT
COALESCE(MAX(isp.Price), 0.00) AS price1,
MAX(COALESCE(isp.Price, 0.00)) AS price2,
iu.unit_id,
iu.unit_name
FROM ITEM_SUPPLIER_PRICE isp
INNER JOIN Items i ON i.item_id = isp.Item_id
INNER JOIN itemunits iu ON iu.unit_id = i.Item_unit_id
WHERE i.Item_id = 7
GROUP BY
iu.unit_id,
iu.unit_name,
isp.update_date
ORDER BY isp.update_date desc;

Complete Select Statement ELSE a defaulted value?

I'm wondering if there is a way to have a complete select statement and if no row is returned to return a row with a default value in a specific field (SQL Server)? Here's a generic version of my SQL to better explain:
SELECT COUNT(CASE WHEN CAST(c.InjuryDate as DATE)>DATEADD(dd,-60, getdate ()) THEN b.InjuryID end) InjuryCount, a.PersonID
FROM Person_Info a
JOIN Injury_Subject b on b.PersonID=a.PersonID
JOIN Injury_Info c on c.InjuryID=b.InjuryID
WHERE EXISTS (SELECT * FROM Hospital_Record d WHERE d.PersonID=b.PersonID and d.InjuryID=b.InjuryID) --There could be multiple people associated with the same InjuryID
GROUP BY a.PersonID
If NOT EXISTS (SELECT * FROM Hospital_Record d WHERE d.PersonID=a.PersonID) THEN '0' in InjuryCount
I want a row for each person who has had an injury to display. Then I'd like a count of how many injuries resulted in hospitalizations in the last 60 days. If they were not hospitalized, I'd like the row to still be generated, but display '0' in InjuryCount column. I've played with this a bunch, moving my date from the WHERE to the SELECT, trying IF ELSE combos, etc. Could someone help me figure out how to get what I want please?
It's hard to tell without an example of input and desired output, but I think this is what you are going for:
select
InjuryCount = count(case
when cast(ii.InjuryDate as date) > dateadd(day,-60,getdate())
then i.InjuryId
else null
end
)
, p.PersonId
from Person_Info p
left join Hosptal_Record h on p.PersonId = h.PersonId
left join Injury_Subject i on i.PersonId = h.PersonId
and h.InjuryId = i.InjuryId
left join Injury_Info ii on ii.InjuryId = i.InjuryId
group by p.PersonId;

How to supply multiple values in between clause after where clause

SELECT
ROW_NUMBER() OVER (ORDER BY Vendor_PrimaryInfo.Vendor_ID ASC) AS RowNumber,
*
FROM
Unit_Table
INNER JOIN
Vendor_Base_Price ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID
INNER JOIN
Vendor_PrimaryInfo ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID
INNER JOIN
Vendor_Registration ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID
AND Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID
INNER JOIN
Category_Table ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN
Vendor_Value_Table ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID
LEFT JOIN
Feature_Table ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
WHERE
Vendor_Registration.Category_ID = 5
AND Vendor_PrimaryInfo.City = 'City'
AND (value_text in ('sample value') or
(SELECT
CASE WHEN ISNUMERIC(value_text) = 1
THEN CAST(value_text AS INT)
ELSE -1
END) BETWEEN 0 AND 100)
As column has multiple values which may be text or may be int that's why I cast based on case. My question is: I just want to fetch the records either whose value is between 0 and 100 or value between 300 to 400 or value is like sample value.
I just want to place the condition after where clause and do not want to use column_name multiple time in between operator because these values are coming from url
Thanks in advance any help would be grateful.
You can try this way..
WHERE
Vendor_Registration.Category_ID = 5
AND Vendor_PrimaryInfo.City = 'City'
AND (value_text in ('sample value') or
(CASE WHEN (ISNUMERIC(value_text) = 1)
THEN CAST(value_text AS INT)
ELSE -1
END) BETWEEN 0 AND 100)

TSQL - Return recent date

Having issues getting a dataset to return with one date per client in the query.
Requirements:
Must have the recent date of transaction per client list for user
Will need have the capability to run through EXEC
Current Query:
SELECT
c.client_uno
, c.client_code
, c.client_name
, c.open_date
into #AttyClnt
from hbm_client c
join hbm_persnl p on c.resp_empl_uno = p.empl_uno
where p.login = #login
and c.status_code = 'C'
select
ba.payr_client_uno as client_uno
, max(ba.tran_date) as tran_date
from blt_bill_amt ba
left outer join #AttyClnt ac on ba.payr_client_uno = ac.client_uno
where ba.tran_type IN ('RA', 'CR')
group by ba.payr_client_uno
Currently, this query will produce at least 1 row per client with a date, the problem is that there are some clients that will have between 2 and 10 dates associated with them bloating the return table to about 30,000 row instead of an idealistic 246 rows or less.
When i try doing max(tran_uno) to get the most recent transaction number, i get the same result, some have 1 value and others have multiple values.
The bigger picture has 4 other queries being performed doing other parts, i have only included the parts that pertain to the question.
Edit (2011-10-14 # 1:45PM):
select
ba.payr_client_uno as client_uno
, max(ba.row_uno) as row_uno
into #Bills
from blt_bill_amt ba
inner join hbm_matter m on ba.matter_uno = m.matter_uno
inner join hbm_client c on m.client_uno = c.client_uno
inner join hbm_persnl p on c.resp_empl_uno = p.empl_uno
where p.login = #login
and c.status_code = 'C'
and ba.tran_type in ('CR', 'RA')
group by ba.payr_client_uno
order by ba.payr_client_uno
--Obtain list of Transaction Date and Amount for the Transaction
select
b.client_uno
, ba.tran_date
, ba.tc_total_amt
from blt_bill_amt ba
inner join #Bills b on ba.row_uno = b.row_uno
Not quite sure what was going on but seems the Temp Tables were not acting right at all. Ideally i would have 246 rows of data, but with the previous query syntax it would produce from 400-5000 rows of data, obviously duplications on data.
I think you can use ranking to achieve what you want:
WITH ranked AS (
SELECT
client_uno = ba.payr_client_uno,
ba.tran_date,
be.tc_total_amt,
rnk = ROW_NUMBER() OVER (
PARTITION BY ba.payr_client_uno
ORDER BY ba.tran_uno DESC
)
FROM blt_bill_amt ba
INNER JOIN hbm_matter m ON ba.matter_uno = m.matter_uno
INNER JOIN hbm_client c ON m.client_uno = c.client_uno
INNER JOIN hbm_persnl p ON c.resp_empl_uno = p.empl_uno
WHERE p.login = #login
AND c.status_code = 'C'
AND ba.tran_type IN ('CR', 'RA')
)
SELECT
client_uno,
tran_date,
tc_total_amt
FROM ranked
WHERE rnk = 1
ORDER BY client_uno
Useful reading:
Ranking Functions (Transact-SQL)
ROW_NUMBER (Transact-SQL)
WITH common_table_expression (Transact-SQL)
Using Common Table Expressions

Resources