I have a main data set called "IncomeRecievedGeneralNeeds". This is what is used on the main report. This includes a field called "Scheme"
I have created a new dataset called "scheme" and a parameter called scheme, but I only want the scheme parameter to show schemes that are in the main dataset.At present it is showing me schemes that are not in the main dataset.
The Scheme code is here -
SELECT DISTINCT loc.scheme AS 'Scheme'
FROM ih_location loc
The IncomeRecievedGeneralNeeds code is here -
SELECT DISTINCT trans.tncy_sys_ref AS 'TncySysRef'
,ten.tenancy_ref AS 'TenancyRef'
,trans.created_date AS 'TransactionCreatedDate'
,MHS.startdate AS 'StartofWeekDate'
,MHS.enddate AS 'EndofWeekDate'
,MHS.financialyear AS 'TransactionFiscalYear'
,MHS.monthname AS 'TransactionFiscalMonthName'
,MHS.month AS 'TransactionFiscalMonth'
,MHS.week AS 'TransactionFiscalWeek'
,CONCAT('Week ',
MHS.week,
' (',
CONVERT(varchar(11),MHS.startdate,103),
'-',
CONVERT(varchar(11),MHS.enddate,103),
')'
) AS 'TransactionFiscalWeekWithDates'
,trans.comment_ AS 'TransactionComment'
,trans.trans_amt AS 'TransactionAmount'
,CASE WHEN trans.account_type IN ('IN','LI') Then 'Income'
WHEN trans.account_type = 'HB' Then 'HousingBenefit'
ELSE '' END AS 'AccountType'
,trans.account_type
,ACC.description AS 'AccountCode'
,loc.scheme AS 'Scheme'
,loc.mgt_area AS 'Management Area'
,loc.location_type AS 'Location Type'
,loct.description AS 'Location Type Description'
,ten.tncy_start AS 'TenancyStartDate'
,ten.tncy_end AS 'TenancyEndDate'
,CASE WHEN ten.tncy_end IS NULL
OR TRANS.created_date < ten.tncy_end
THEN 'Current' ELSE 'Former' END AS 'IncomeTenancyStatus'
,ten.tncy_status AS 'TenanacyStatus'
,CASE WHEN ten.tncy_status = 'FOR' THEN LOC.former_arrs_ofcr ELSE loc.arrears_ofcr END AS 'OfficerCode'
FROM [dbo].[re_tncy_trans] trans
INNER JOIN
re_tenancy ten
ON trans.tncy_sys_ref = ten.tncy_sys_ref
INNER JOIN
re_tncy_place tenpl
ON TEN.tncy_sys_ref = tenpl.tncy_sys_ref
INNER JOIN
ih_location loc
ON tenpl.place_ref = loc.place_ref
INNER JOIN
[dbo].[re_accounts] acc
ON
trans.account_code = ACC.account_code
AND trans.account_type = acc.account_type
INNER JOIN
[mhsInsight].[dbo].[mhs_month_week] mhs
ON trans.created_date BETWEEN mhs.startdate AND MHS.enddate
INNER JOIN
[dbo].[ih_location_type] AS loct
ON loc.location_type = LOCT.location_type
WHERE trans.account_type IN ('IN','HB','LI')
AND MHS.startdate >= CONVERT(DATETIME, '2014-04-07 00:00:00', 102)
and loc.place_ref <> '9999999999'
In your parameter query, use the same FROM and WHERE clause that you use in your main query, and you will only get the same Schemes that you have in your main dataset.
Related
I have multiple models in Sparx Enterprise Architect in file-based, i.e. using MS access.
I'm using a custom template to populate a table with data from object's properties, including some with <memo> fields.
This is the query i'm using in the template fragment:
SELECT obj.object_id,
obj.Stereotype,
objp.Property as Prop,
switch(objp.Value = '<memo>', objp.Notes, objp.Value LIKE '{*}',
NULL, 1=1, objp.Value) AS Val,
(SELECT tobj2.ea_guid & tobj2.Name FROM t_object tobj2 WHERE
tobj2.ea_guid = objp.Value) AS [Obj-Hyperlink]
FROM t_object obj
INNER JOIN t_objectproperties objp
ON (obj.object_id = objp.object_id)
WHERE obj.object_id = #OBJECTID# AND obj.Stereotype='Data-
Stream' AND objp.Property NOT IN ('isEncapsulated')
ORDER BY objp.Property ASC;
I found that the when these fields are longer than 249 chars I get an error message when generating the reports and the cell in the generated table is simply empty. This is also noticeable with a query:
The error I'm getting states:
"Error Processing xml document: an invalid character was found in text context"
Is there any workarround to enable including the <memo> fields' data with more than 249 chars in the reports?
Any help is much appreciated.
I've found a workaround for this by joining two queries with a "Union all". The first query will handle the non-memo fields with the switch function and the second one the memo fields without the switch function.
select
obj.object_id,
obj.Stereotype,
objp.Property as Prop,
objp.Notes AS Val,
(
SELECT
tobj2.ea_guid & tobj2.Name
FROM
t_object tobj2
WHERE
tobj2.ea_guid = objp.Value
) AS [Obj-Hyperlink]
from
t_objectproperties objp
left join t_object obj on (obj.object_id = objp.object_ID)
where
obj.object_id = #OBJECTID#
AND obj.Stereotype = 'Data-Stream'
AND objp.Property NOT IN ('isEncapsulated')
AND objp.Value = "<memo>"
UNION ALL
SELECT
obj2.object_id,
obj2.Stereotype,
objp2.Property as Prop,
switch(
objp2.Value LIKE '{*}', NULL, 1 = 1, objp2.Value
) AS Val,
(
SELECT
tobj2.ea_guid & tobj2.Name
FROM
t_object tobj2
WHERE
tobj2.ea_guid = objp2.Value
) AS [Obj-Hyperlink]
FROM
t_object obj2
INNER JOIN t_objectproperties objp2 ON (obj2.object_id = objp2.object_id)
WHERE
obj2.object_id = #OBJECTID#
AND obj2.Stereotype = 'Data-Stream'
AND objp2.Property NOT IN ('isEncapsulated')
and objp2.Value <> "<memo>"
order by
3 asc;
Thanks a lot #geertbellekens for your comment which was crucial to find this solution.
I have a query that takes 15 seconds to get 350 results in a MySQL 5.6 Server and I am unable to diagnose why, I am still very new to database optimizing. U
The EXPLAIN visual does show some non-unique key lookups but each only says one 1 row look up.
The tabular EXPLAIN which I am not able to interpret and I am hoping someone else can here looks like .
I have tried switching the ending LIMIT = 350 to 100, 10, and the query takes exactly the same amount of time to run, about 15 seconds.
I have tried nixing the views but besides making it hard to recreate this query it did not improve performance.
Perhaps related, in other EXPLAIN statements in our MySQL DB, I've seen a view referenced with Materialized next to it, but that does not appear near next to any of the three views used in this query, in fact I don't even see the views referenced at all instead only the tables they reference. Is that a factor?
My last attempt was replacing the final selected column which is a listlineitems.* with the specific columns, since I've read that can improve speed and is just better practice, but I get the sense that is not going to dramatically improve this situation.
Here's the query -
SELECT
0 AS 'Check',
DATE_FORMAT(`listlineitems`.`dateEntered`,
'%Y-%m-%d') AS 'Date Entered',
`listlineitems`.`itemId` AS 'parentTableIdx',
`listlineitems`.`parentProjectId` AS 'parentProjectIdx',
`listlineitems`.`idx` AS 'ID',
IF(`listlineitems`.`active` = 1,
'Active',
'Inactive') AS 'Active/Inactive',
CONCAT(`listUsers`.`FirstName`,
' ',
`listUsers`.`LastName`) AS 'Employee',
CASE `listlineitems`.`type`
WHEN 1 THEN 'Time Entry'
WHEN 2 THEN 'Expense Entry'
END AS 'Type',
`listcustomers`.`name` AS 'Customer',
`listlocations`.`name` AS 'Location',
`listareas`.`name` AS 'Area',
`listassets`.`name` AS 'Asset',
`listprojects`.`name` AS 'Project',
`listprojects`.`number` 'Project #',
`listprojects`.`autoassign` 'autoassign',
`listactivities`.`name` AS 'Activity',
(CASE `listlineitems`.`type`
WHEN 1 THEN `listlineitems`.`qty`
WHEN 2 THEN `listlineitems`.`qty`
END) AS 'Quantity',
`listlineitems`.`taxable` AS 'Taxable',
`listlineitems`.`totalAmount` - `listlineitems`.`taxAmount` AS 'Pre-Tax Amount',
`listlineitems`.`taxAmount` AS 'Tax Amount',
`listlineitems`.`totalAmount` AS 'Total Amount',
`listCustomers`.`idx` AS 'parentCustomerIdx',
`listLocations`.`idx` AS 'parentLocationIdx',
`listAreas`.`idx` AS 'parentAreaIdx',
`listAssets`.`idx` AS 'parentAssetIdx',
CONCAT(`listcustomers`.`name`,
'/',
`listlocations`.`name`,
'/',
`listareas`.`name`,
'/',
`listassets`.`name`,
'/',
`listprojects`.`name`) AS 'Path',
IF(`listlineitems`.`customerViewable` = 1,
'Yes',
'No') AS 'Cust. Viewable',
(CASE
WHEN `listlineitems`.`type` = 2 THEN `listexpenseentry`.`TotalCostToPSI` - `listexpenseentry`.`TaxCostToPSI`
ELSE `listlineitems`.`totalAmount` - `listlineitems`.`taxAmount`
END) AS 'preTaxCostPSI',
(CASE
WHEN `listlineitems`.`type` = 2 THEN `listexpenseentry`.`TaxCostToPSI`
ELSE `listlineitems`.`taxAmount`
END) AS 'taxCostPSI',
(CASE
WHEN `listlineitems`.`type` = 2 THEN `listexpenseentry`.`TotalCostToPSI`
ELSE `listlineitems`.`totalAmount`
END) AS 'totalCostPSI',
view_solinx2.lastAltered AS 'lastalteredSO',
view_polinx2.lastAlteredPO AS 'lastalteredPO',
view_invlinx2.lastAlteredInv AS 'lastalteredInv',
view_solinx2.lastAlteredAfterConfirmation AS 'lastAlteredAfterConfirmation',
view_solinx2.roleIdSO AS 'roleIdSO',
view_polinx2.roleIdPO AS 'roleIdPO',
view_polinx2.userIdPO AS 'userIdPO',
view_polinx2.lastAlteredafterConfirmation AS 'lastAlteredAfterConfirmationPO',
view_invlinx2.roleIdInv AS 'roleIdInv',
view_invlinx2.userIdInv AS 'userIdInv',
view_invlinx2.lastAlteredafterConfirmation AS 'lastAlteredAfterConfirmationInv',
view_solinx2.roleId AS 'roleId',
view_solinx2.userId AS 'userId',
view_solinx2.soId AS 'SOId',
view_solinx2.autoassignSO AS 'autoassignSO',
IF(view_solinx2.notNeeded = 1,
'Not Needed',
view_solinx2.number) AS 'SOname',
view_solinx2.dateEntered AS 'SoDate',
view_solinx2.totalSOAmount AS 'SoTotal',
view_invlinx2.invId AS 'InvId',
IF(view_solinx2.notNeeded = 1,
'------',
view_invlinx2.`number`) AS 'InvName',
view_invlinx2.dateEntered AS 'InvDate',
view_invlinx2.amount AS 'InvTotal',
view_polinx2.poId AS 'POId',
IF(view_solinx2.notNeeded = 1,
'------',
view_polinx2.`number`) AS 'POName',
view_polinx2.dateEntered AS 'PODate',
view_polinx2.amount AS 'POTotal',
(SELECT
listsalesorders.number
FROM
listsalesorders
WHERE
listsalesorders.idx = autoassign) AS 'test',
`listlineitems`.*
FROM
`listlineitems`
LEFT JOIN
`listUsers` ON `listlineitems`.`individualId` = `listUsers`.`idx`
LEFT JOIN
`listprojects` ON `listlineitems`.`parentProjectId` = `listprojects`.`idx`
LEFT JOIN
`listassets` ON `listlineitems`.`parentAssetId` = `listassets`.`idx`
LEFT JOIN
`listareas` ON `listlineitems`.`parentAreaId` = `listareas`.`idx`
LEFT JOIN
`listlocations` ON `listlineitems`.`parentLocationId` = `listlocations`.`idx`
LEFT JOIN
`listcustomers` ON `listlineitems`.`parentCustomerId` = `listcustomers`.`idx`
LEFT JOIN
`listactivities` ON `listactivities`.`idx` = `listlineitems`.`activityCode`
LEFT JOIN
`listexpenseentry` ON (`listexpenseentry`.`idx` = `listlineitems`.`itemId`
AND `listlineitems`.`type` = 2)
LEFT JOIN
view_solinx2 ON view_solinx2.idx = listlineitems.idx
LEFT JOIN
view_polinx2 ON view_polinx2.idx = listlineitems.idx
LEFT JOIN
view_invlinx2 ON view_invlinx2.idx = listlineitems.idx
GROUP BY `listlineitems`.`idx`
ORDER BY `listlineitems`.`dateEntered` DESC
LIMIT 10;
I am at a loss as to what else I can do to improve this and any suggestions are very much appreciated.
You are selecting everything from listlineitems table (100+ K records), joining many tables, then grouping by idx and then throwing out most results.
You can:
Try to add unique index (dateEntered, idx) to listlineitems
Try limit listlineitems by dateEntered if acceptable (WHERE dateEntered > DATE_SUB(NOW(), INTERVAL 30 DAYS)). dateEntered must be indexed
Try to put select from listlineitems + grouping + limit into subquery so MySQL will do joins to only these 10 rows returned by subquery.
Convert dependent subquery (listsalesorders) to left join
*** SOLUTION IN BOTTOM****
I am trying to add some comment at last column of my query , basically if technical_document.disc_id contains "KN" then i want to add a comment to the last column of query 'OK'
but i cant get it working
SELECT
technical_document.project_no,
technical_document.doc_no,
technical_document.doc_class,
technical_document.disc_id,
tag_document.project_id AS "COMMENT"
CASE WHEN technical_document.disc_id = 'KN' THEN tag_document.project_id = "YES"
FROM technical_document left join tag_document on technical_document.doc_no = tag_document.proj_doc_doc_no
WHERE tag_document.proj_doc_doc_no IS NULL
AND technical_document.project_no like '%%'
AND technical_document.doc_class = ANY ('A','S','SE')
AND technical_document.Lci_Code = ANY ('A','A1','B')
Thanks for your help, here is how it was solved, sorry for confusing/misleading explanation on my part:
SELECT
technical_document.project_no,
technical_document.doc_no,
technical_document.doc_class,
technical_document.disc_id,
CASE
WHEN technical_document.disc_id LIKE 'KN' THEN 'OK'
WHEN technical_document.disc_id LIKE 'K6' THEN 'OK'
ELSE null
END
FROM technical_document left join tag_document on technical_document.doc_no = tag_document.proj_doc_doc_no
WHERE tag_document.proj_doc_doc_no IS NULL
AND technical_document.project_no like '%%'
AND technical_document.doc_class = ANY ('A','S','SE')
AND technical_document.Lci_Code = ANY ('A','A1','B')
I would write the query as:
SELECT d.project_no, d.doc_no, d.doc_class, d.disc_id,
d.project_id AS COMMENT,
(CASE WHEN td.disc_id = 'KN' THEN td.project_id = 'YES' END)
FROM technical_document d LEFT JOIN
tag_document td
ON d.doc_no = td.proj_doc_doc_no
WHERE d.proj_doc_doc_no IS NULL AND
d.project_no like '%%' AND -- not needed
d.doc_class IN ('A', 'S', 'SE') AND
d.Lci_Code IN ('A', 'A1', 'B');
First, you have a WHERE clause that says that there is no match. Hence, including columns in the SELECT from tag_document doesn't make sense. I suspect you intend:
SELECT d.project_no, d.doc_no, d.doc_class, d.disc_id,
d.project_id as COMMENT,
(CASE WHEN td.disc_id = 'KN' THEN td.project_id = 'YES' END)
FROM technical_document d LEFT JOIN
tag_document td
ON d.doc_no = td.proj_doc_doc_no AND td.disc_id = 'KN'
WHERE d.project_no like '%%' AND -- not needed
d.doc_class IN ('A', 'S', 'SE') AND
d.Lci_Code IN ('A', 'A1', 'B');
Note the condition on td in the WHERE clause has been removed.
In addition:
Table aliases make the query easier to write and to read.
= ANY is allowed, but the colloquial operator is IN.
Various small syntax errors are fixed -- missing commas, missing END.
I am working on the following query:
declare #start date = '06/01/2016';
declare #end date = '07/31/2017';
----------------------------------------------------------------------------- ------------------------------------------------
-- Pull all claims with paid date in range parameter
-----------------------------------------------------------------------------
------------------------------------------------
if object_id('LA_Temp.dbo.Item19') is not null drop table LA_Temp.dbo.Item19
select distinct
c.claimid,
c.formtype,
c.facilitycode + c.billclasscode as BillType,
case when primaryclaimid = '' and resubclaimid = '' then 'Clean' else 'Other' end as CleanClaim,
-- DHHClaimtype 04 needs to be broken out based on provider specialty and location
Case when c.formtype = '1500' and cd.location = 21 and ps.specialtycode in ('05','22','1T','1F','30','1C') then '04-Hospitalist'
when c.formtype = '1500' then '04-Other'
else ' '
end as DHHClaimtype,
c.status,
c.totalpaid,
e.phystate as MemberState,
e.phycounty as MemberParish,
pc.ParishCode as MemberParishCode,
con.contracted as NetworkProvider,
reject
into LA_Temp.dbo.Item19
from claim c
inner join member m on c.memid = m.memid
inner join entity e on m.entityid = e.entid
left join LA_Temp.dbo.ParishCodes pc on e.phycounty = pc.Parish
inner join contract con on c.contractid = con.contractid
inner join provider p on c.provid = p.provid
inner join provspecialty ps on p.provid = ps.provid and ps.spectype =
'PRIMARY'
inner join claimdetail cd on c.claimid = cd.claimid and cd.claimline = 1 -- just pull the first line to
grab the location code, exclude any location codes with non-numeric values
where c.paiddate between #start and #end
and c.status in ('PAID','DENIED');
-- add the claim types to the table
EXECUTE LA_Temp.[dbo].[USP_LA_SetDHHClaimType] #Table = 'Item19';
The problem exists in the first case statement. Specifically here:
and cd.location = 21
Upon further investigation of the claimdetail (cd) table, I have found that column cd.location (datatype = int) has 4 values ('H', 'U8', 'A', 'OH') which are onviously not numeric. I would like to convert these values to blanks (if possible, not sure if blanks (' ') are compatible with int datatype) or zeros if blanks will not work. Due to the NonNumeric values, I am getting the following error (which is to be expected):
Msg 245, Level 16, State 1, Line 13
Conversion failed when converting the varchar value 'H ' to data type int.
I am aware that I can exclude these records in either the join clause or in a where statement such as:
Where cd.location not in ('H', 'U8', 'A', 'OH')
However, I want to keep the records that these values are tied to, I just want the cd.location value to be blank when it is one of these 4 values. Can someone show me how I can keep these records, by converting cd.location to ' ' when cd.location in ('H', 'U8', 'A', 'OH').
I think I got it...
Again we are focusing on the first case statement in the originally posted query:
case
-- DHHClaimtype 04 needs to be broken out based on provider specialty and location
When c.formtype = '1500' and cd.location = 21 and ps.specialtycode in ('05','22','1T','1F','30','1C')
Then '04-Hospitalist'
When c.formtype = '1500'
Then '04-Other'
else ' '
end as DHHClaimtype,
Changed to:
case
-- DHHClaimtype 04 needs to be broken out based on provider specialty and location
When c.formtype = '1500' and Case When IsNumeric(cd.location) = 0 Then ''
Else cd.location End = 21 and ps.specialtycode in ('05','22','1T','1F','30','1C') then '04-Hospitalist'
When c.formtype = '1500'
Then '04-Other'
else ' '
end as DHHClaimtype,
So I am using Kentico CMS Desk 7 to generate reports for my company. In Kentico you create parameters and then create a table using sql and those parameters with the # symbol so whatever the user enters into that parameter, it will be the value of a parameter variable like #Status. I am wanting to add the ability for the user to either enter in one value, multiple values, or no values into the parameters, but I do not know how to implement the multiple values. I am a little new to SQL so bear with me. This is the SQL code I have right now:
select
ClaimNumber as 'Claim Number',
CustomerName as 'Customer Name',
DollarAmount as 'Dollar Amount',
[ReasonCode] as 'Reason code',
rt.[ReasonTypeName] as 'Reason type',
PlantNumber as 'Selling Company',
Status as 'Status'
from TABLE1 as c
join TABLE2 as u on u.UserID = c.DocumentCreatedByUserID
left join TABLE3 as rt on rt.ItemId = c.ReasonType
where ClaimDate between #FromDate and #ToDate
and ReasonCode like #ReasonCode
and ReasonType like #ReasonType
and (#SellingCompany = '' or PlantNumber = #SellingCompany)
and Status like #Status
order by ClaimNumber;
The parameter that I am trying to do this with is the selling company parameter denoted as #SellingCompany. Right now, this works for users not entering in any value and users entering in only one value, but I would like for users to have the ability to input multiple values separated by commas. I feel like an IN operator might work, but I am inexperienced in SQL and I don't know how I would implement this. I can't publish the data obviously because there is customer information, but this statement works as it is and I just need to know how to implement what I'm wanting to do. Thanks guys!
Have you tried this?
select
ClaimNumber as 'Claim Number',
CustomerName as 'Customer Name',
DollarAmount as 'Dollar Amount',
[ReasonCode] as 'Reason code',
rt.[ReasonTypeName] as 'Reason type',
PlantNumber as 'Selling Company',
Status as 'Status'
from TABLE1 as c
join TABLE2 as u on u.UserID = c.DocumentCreatedByUserID
left join TABLE3 as rt on rt.ItemId = c.ReasonType
where ClaimDate between #FromDate and #ToDate
and ReasonCode like #ReasonCode
and ReasonType like #ReasonType
and (#SellingCompany = '' or PlantNumber IN (#SellingCompany))
and Status like #Status
order by ClaimNumber;
I use this SQL function specifically when I need to cast a delimited string to a table value to use with the IN operator.
CREATE FUNCTION [dbo].[ParseIDListToTable]
(#vc_Ids nvarchar(MAX))
RETURNS #Id_table TABLE
(ID nvarchar(15))
BEGIN
DECLARE #in_Index1 AS INT, --Used to store ID delimiter(',') position in string
#vc_ID AS NVARCHAR(15)
/* initialize working variables */
SET #in_Index1 = CHARINDEX(',',#vc_Ids)
/* loop through ids in delimited string */
WHILE (#in_Index1 > 0 OR LEN(#vc_Ids) > 0)
BEGIN
/* parse out single id for processing */
IF #in_Index1 > 0
BEGIN
SET #vc_ID = Left(#vc_Ids,#in_Index1 - 1)
SET #vc_Ids = Right(#vc_Ids,Len(#vc_Ids) - #in_Index1)
END
ELSE
BEGIN
SET #vc_ID = #vc_Ids
SET #vc_Ids = ''
END
INSERT #Id_table (ID)
VALUES(#vc_ID)
/* prepare to loop */
SET #in_Index1 = CHARINDEX(',',#vc_Ids)
END
/* return the ids */
RETURN
END
Then I use it in my SELECT statement like so
WHERE PlantNumber IN (SELECT * FROM dbo.ParseIDListToTable('Microsoft,Apple,Dell'))
This should return the results you're looking for.