Number of characters displayed for a SQL based report - sql

I'm trying to modify a report that shows health assessments using SQL. On the report, I would like to add a section for comments that were added to the health assessments. I was able to add the comment section, and with a suggestion provided here, I used SUBSTRING to limit the number of characters displayed on the report to 1000 as opposed to 8000.
The issue I'm experiencing now is with limiting the number of characters displayed for the option 'Other' as shown below. I used SUBSTRING (ex: SUBSTRING(HltNutrition.Comment, 1, 1000)) for all of the assessments and have included the Nutrition assessment as an example (which is working correctly) along with the snippet of code featuring the 'Other' (Chronic) option (which is not working correctly). I replaced 3 with 1 and although this did not produce an error, it did not have the intended effect for 'Other' as SUBSTRING([HealthAssessName].Comment, 1, 1000).
Any assistance is appreciated. Thank you in advance.
-- Nutrition
INSERT INTO #ChronicCondition(IdApplicant, ExamDate, Condition, TreatmentNeeded, TreatmentReceived, Status, Comment)
SELECT #Enroll.IdApplicant,
HltNutrition.ExamDate,
'Nutrition',
HltNutrition.TrtNeed,
HltNutrition.TrtStatus,
HltNutrition.Status,
SUBSTRING (HltNutrition.Comment, 1, 1000)
FROM #Enroll
JOIN HltNutrition ON HltNutrition.IdApplicant = #Enroll.IdApplicant
WHERE HltNutrition.Overweight = 1
-- Chronic
INSERT INTO #ChronicCondition(IdApplicant, ExamDate, Condition, TreatmentNeeded, TreatmentReceived, Status, Comment)
SELECT #Enroll.IdApplicant,
HltChronic.ExamDate,
CASE ChronicCondition.Id
WHEN 3 THEN 'Other' + ISNULL(' - ' + hltChronic.ConditionOther, '')
ELSE ChronicCondition.Condition
END,
HltChronic.TrtNeed,
HltChronic.TrtStatus,
hltChronic.Status,
SUBSTRING (HltChronic.Comment, 1, 1000)
FROM #Enroll
JOIN hltChronic ON hltChronic.idApplicant = #Enroll.idApplicant
JOIN ChronicCondition ON ChronicCondition.Id = hltChronic.Condition

Thank you for the assistance, I walked through the concern with the senior developer and found that the SUBSTRING function was not the cause of the issue. The problem I was encountering was due to data entry that was used for testing the report. The code I added is actually correct and the problem has been resolved.
Thanks again for any assistance that was provided.

Related

String Matching query in BIGQUERY times out

I have a select statement:
select
M.FA_Unique_Listing_Identifier_Ref_ID
,P.ATTOM_ID
,P.ParcelNumberRaw Parcel
,M.Assessors_Parcel_Identification_Number
,M.Listing_Tracking_ID
,P.CensusTract GEOID
,M.Current_Original_Listing_Date
,M.Add_Change_Delete_Indicator
,M.FA_Calculated_Days_on_Market
,M.Status
,M.Status_Sub_Type
,M.Update_Timestamp
,M.LoadDate
,'Parcel Match' as Match_Type
from `mother-stg-254212.DATATREE_MLS.MLS_STAGE` M
JOIN `mother-216719.PROPERTY.PROPERTY_DETAIL` P on
M.Property_Address = P.PropertyAddressFull
and M.Property_Zip = P.PRopertyAddressZIP
but this query times out.
THe two matching fields Address and Zip are Strings.
It runs 6 hours and times out.
How can I make this work faster?
Thanks
This looks like an unbalanced joins scenario.
For this you could either try to optimize your join patterns. If the issue persists after this, I suggest opening an issue tracker so the BigQuery engineering team can verify this behavior.

Completely Unique Rows and Columns in SQL

I want to randomly pick 4 rows which are distinct and do not have any entry that matches with any of the 4 chosen columns.
Here is what I coded:
SELECT DISTINCT en,dialect,fr FROM words ORDER BY RANDOM() LIMIT 4
Here is some data:
**en** **dialect** **fr**
number SFA numero
number TRI numero
hotel CAI hotel
hotel SFA hotel
I want:
**en** **dialect** **fr**
number SFA numero
hotel CAI hotel
Some retrieved rows would have something similar with each other, like having the same en or the same fr, I would like to retrieved rows that do not share anything similar with each other, how do I do that?
I think I’d do this in the front end code rather the dB, here’s a pseudo code (don’t know what your node looks like):
var seenEn = “en not in (''“;
var seenFr = “fr not in (''“;
var rows =[];
while(rows.length < 4)
{
var newrow = sqlquery(“SELECT *
FROM table WHERE “ + seenEn + “) and ”
+ seenFr + “) ORDER BY random() LIMIT 1”);
if(!newrow)
break;
rows.push(newrow);
seenEn += “,‘“+ newrow.en + “‘“;
seenFr += “,‘“+ newrow.fr + “‘“;
}
The loop runs as many times as needed to retrieve 4 rows (or maybe make it a for loop that runs 4 times) unless the query returns null. Each time the query returns the values are added to a list of values we don’t want the query to return again. That list had to start out with some values (null) that are never in the data, to prevent a syntax error when concatenation a comma-value string onto the seenXX variable. Those syntax errors can be avoided in other ways like having a Boolean of “if it’s the first value don’t put the comma” but I chose to put dummy ineffective values into the sql to make the JS simpler. Same goes for the
As noted, it looks like JS to ease your understanding but this should be treated as pseudo code outlining a general algorithm - it’s never been compiled/run/tested and may have syntax errors or not at all work as JS if pasted into your file; take the idea and work it into your solution
Please note this was posted from an iphone and it may have done something stupid with all the apostrophes and quotes (turned them into the curly kind preferred by writers rather than the straight kind used by programmers)
You can use Rank or find first row for each group to achieve your result,
Check below , I hope this code will help you
SELECT 'number' AS Col1, 'SFA' AS Col2, 'numero' AS Col3 INTO #tbl
UNION ALL
SELECT 'number','TRI','numero'
UNION ALL
SELECT 'hotel','CAI' ,'hotel'
UNION ALL
SELECT 'hotel','SFA','hotel'
UNION ALL
SELECT 'Location','LocationA' ,'Location data'
UNION ALL
SELECT 'Location','LocationB','Location data'
;
WITH summary AS (
SELECT Col1,Col2,Col3,
ROW_NUMBER() OVER(PARTITION BY p.Col1 ORDER BY p.Col2 DESC) AS rk
FROM #tbl p)
SELECT s.Col1,s.Col2,s.Col3
FROM summary s
WHERE s.rk = 1
DROP TABLE #tbl

SQL AverageIFS Equivalent for Query

So I'm extremely new to using SQL. This syntax formatting is offensive but I am editing it in notepad and can't figure out a better alternative. I want it in the .dqy format but I don't know how else to edit. So if you have a suggestion please advise..
A general description: There is that SUM(CASE WHEN ...) portion of code below that I'm trying to get to work. I'm making an exception report, and I want another column that is the conditional average based on my concatenated value exclusive of that entry. IE, in Excel this is an easy formula (Column I):
=+IFERROR(AVERAGEIFS(H:H,C:C,[#Cust],A:A,"<>"&[#[Order Number]]),0)
Except I want to have it pull as part of the query.
Here is a picture of the output:
Here is my SQL. Again I know formatting stinks if there is a different program than notepad that I can edit a .dqy in please advise. Also, what do those 3's mean in the 6th line of my code. I took a query from something else and have been modifying it into this project.
XLODBC
1
DRIVER=SQL Server;
SERVER=*OMIT*;
UID=*OMIT*;
Trusted_Connection=Yes;
APP=Microsoft Office 2010;
WSID=*OMIT*;
DATABASE=*OMIT*
SELECT DISTINCT RMORHP.ORHORDNUM AS 'Order Number',
RMORHP.ORHCRTDTE AS 'Order Create Date',
CONCAT(RMORHP.ORHCUSCHN, '-', RMORHP.ORHCUSNUM) AS 'Cust',
RMORHP.ORHCUSCHN AS 'Chain ID',
RMORHP.ORHCUSNUM AS 'Cust ID',
RMCUSP.CUSCUSNAM AS 'Customer',
RMORHP.ORHCRTUSR AS 'Created By',
RMORHP.ORHORDQTY AS 'Units Ordered',
SUM(CASE
WHEN RMCUSP.CUSCUSNAM = RMCUSP.CUSCUSNAM
THEN RMORHP.ORHORDQTY
END)
GROUP BY RMCUSP.CUSCUSNAM AS 'Total Units'
FROM BIDW_DataLake.erms.RMORHP RMORHP,
BIDW_DataLake.eRMS.RMCUSP RMCUSP
WHERE (RMORHP.ORHCRTDTE BETWEEN ? AND ?)
AND RMCUSP.CUSCUSCHN = RMORHP.ORHCUSCHN
AND RMCUSP.CUSCUSNUM = RMORHP.ORHCUSNUM
AND RMCUSP.CUSDFTDCN = 505
enter
START date "yyyymmdd" enter END date "yyyymmdd"
3 3
Order Number Create Date Cust Chain ID Cust ID Customer Created By
It looks like you are trying to get the average order quantity for other order a customer has made during a given date range. To say it another way: The average of a given customer's orders not including the order in the current row.
If that's correct, you might try replacing the SQL portion of your query with this:
SELECT R1.ORHORDNUM AS 'Order Number',
R1.ORHCRTDTE AS 'Order Create Date',
CONCAT(RMORHP.ORHCUSCHN, '-', RMORHP.ORHCUSNUM) AS 'Cust',
R1.ORHCUSCHN AS 'Chain ID',
R1.ORHCUSNUM AS 'Cust ID',
RMCUSP.CUSCUSNAM AS 'Customer',
R1.ORHCRTUSR AS 'Created By',
R1.ORHORDQTY AS 'Units Ordered',
(SELECT AVG(R2.HORDQTY)
FROM BIDW_DataLake.erms.RMORHP R2
WHERE R2.ORHCUSNUM = R1.ORHCUSNUM
AND R2.ORHORDNUM <> R1.ORHORDNUM) as 'Total Units'
FROM BIDW_DataLake.erms.RMORHP R1,
BIDW_DataLake.eRMS.RMCUSP RMCUSP
WHERE (RMORHP.ORHCRTDTE BETWEEN ? AND ?)
AND RMCUSP.CUSCUSCHN = R1.ORHCUSCHN
AND RMCUSP.CUSCUSNUM = R1.ORHCUSNUM
AND RMCUSP.CUSDFTDCN = 505
The Total Units column is what is known as a correlated subquery. Consider researching that.
What makes this a bad answer:
I have no way of testing it, and I'm not 100% certain of the
MS-Query syntax where Excel connects with SQL Server.
MS-Query may not support correlated subqueries in this way.
I don't quite understand how the parameterized portion of the query works. That is, clearly it looks like the query is meant to ask for a start and end date and put those where the question marks go. I'm trusting that it works as-is. (Though, I suspect this is where your "3 3" is coming from.
So, probably vote this answer down and thrash me soundly for giving a bad answer, but maybe you will get something from it. I just thought it was too much to try to put in a comment.
I din't totally understand the example but for a general case you can use:
AVG(CASE WHEN [condition1] and [condition2] THEN [the value you want to average] Else NULL END).
This shoud return the average if the column fir all the rows that meet your conditions.

query replace blank

My query draws the total cost from two other queries and then adds these together to generate a job cost total. My issue is that when a job is entered and the query runs its magic in the background, dependant on the job means that one field may not contain any cost information. I believe it to be because of these empty cells that the totals do not populate correctly and thus will need to replace the blanks with £0.
https://i.stack.imgur.com/zcnk2.png
https://i.stack.imgur.com/OWJdX.png
SELECT tblMaintenanceLog.LogID, Last(QIntTotals.IntTotal) AS LastOfIntTotal, Last(QExtPartsTotalsComp.SumOfSumOfEXTPCost) AS LastOfSumOfSumOfEXTPCost, [IntTotal]+[SumOfSumOfEXTPCost] AS Expr1
FROM (tblMaintenanceLog LEFT JOIN QIntTotals ON tblMaintenanceLog.LogID = QIntTotals.INTJobID) LEFT JOIN QExtPartsTotalsComp ON tblMaintenanceLog.LogID = QExtPartsTotalsComp.EXTPJobID
GROUP BY tblMaintenanceLog.LogID, [IntTotal]+[SumOfSumOfEXTPCost]
ORDER BY tblMaintenanceLog.LogID;
I have tried an if statement to replace blanks with 0 and also the Nz function without any avail. However, I could just be entering it in wrong as I am still relatively new to VBA and SQL so any help would be greatly appreciated!
Thank you all :)
You can use COALESCE in this case.
SELECT tblMaintenanceLog.LogID , COALESCE(NULLIF(Last(QIntTotals.IntTotal),''),0) AS LastOfIntTotal, Last(QExtPartsTotalsComp.SumOfSumOfEXTPCost) AS LastOfSumOfSumOfEXTPCost, [IntTotal]+[SumOfSumOfEXTPCost] AS Expr1
FROM (tblMaintenanceLog LEFT JOIN QIntTotals ON tblMaintenanceLog.LogID = QIntTotals.INTJobID) LEFT JOIN QExtPartsTotalsComp ON tblMaintenanceLog.LogID = QExtPartsTotalsComp.EXTPJobID
GROUP BY tblMaintenanceLog.LogID, [IntTotal]+[SumOfSumOfEXTPCost]
ORDER BY tblMaintenanceLog.LogID;
I have the answer!!
Iif(Last(QIntTotals.IntTotal) is null, 0, Last(QIntTotals.IntTotal))
I cant thank you enough for your help ppijnenburg! I didn't realise how to properly add stuff in SQL until you shown me that! You have saved me much heartache!!!! Thank you :)

SQL / SSRS 2008 - How to combine 2 conditions into a single condition in the WHERE clause?

I have a requirement which appears simple enough but i cannot get this to work. I want to exclude a particular record in my resultset that meets TWO conditions, click the following image to see my current resultset: https://i.stack.imgur.com/z93m3.png . I want to exclude any lines that have both a selling_price of £84.99 AND a vat_value of £40.83, in my case that would mean i want the last line of my resultset image excluded.
I've attempted to use the following as my SQL code:
SELECT created_by, sales_order_number, sales_order_credit_line, qty_credited, sales_order_line, selling_price, vat_value
FROM sales_order_credit
WHERE (selling_price <> 84.99 AND vat_value <> 40.83)
However, as soon as i go to then run the query, the Query Designer reformats my code to read:
SELECT created_by, sales_order_number, sales_order_credit_line, qty_credited, sales_order_line, selling_price, vat_value
FROM sales_order_credit
WHERE (selling_price <> 84.99) AND (vat_value <> 40.83)
Because my code now reads like that, it excludes all lines with a selling price of £84.99 and all lines with a vat_value of £40.83, which is not what i want - i only want to exclude lines that adhere to BOTH of those conditions.
I've ran into this before and never known how this should be done - any help is really appreciated.
Jacob
EDIT - Responses to Comments
VKP - thanks for your suggestion, when i add your code it changes to:
SELECT created_by, sales_order_number, sales_order_credit_line, qty_credited, sales_order_line, selling_price, vat_value
FROM sales_order_credit
WHERE (NOT (selling_price = 84.99))
OR
(NOT (vat_value = 40.83))
Again, it takes the two and puts them into completely seperate conditions seperated by OR - which is not what im looking for
Ubiquitous Developers - there is a difference, if you do the reformatted version of the code it will exclude line 4 AND 2, whereas i only want line 4 excluded as it meets both conditions, whereas line 2 only met 1 of the conditions (selling_price)
I think the right thing to do in your case is the next:
SELECT created_by, sales_order_number, sales_order_credit_line, qty_credited, sales_order_line, selling_price, vat_value
FROM sales_order_credit
WHERE NOT (selling_price = 84.99 AND vat_value = 40.83)
WHERE (selling_price <> 84.99) OR (vat_value <> 40.83)
Try it yourself: rextester