This is my code for a query to produce a specific report. This works, however when I added the last select statement
(Select Name
from RPT_CUSTOM_LIST_VALUES
where CUSTOM_PROPERTY_VALUE_ID = RI1.CUST_10) AS [Application]
The RI1.Cust_10 column holds multiple values delimited by commas. How can I get it so that the look up table pulls each value and provides the correct name for that value? I cannot create or modify the tables within this database.
select
RI1.incident_id as [Project Incident #],
(Select Name from RPT_CUSTOM_LIST_VALUES
where CUSTOM_PROPERTY_VALUE_ID = RI1.CUST_02) as [Business Name],
RI1.NAME as [Project Name],
RI1.INCIDENT_STATUS_NAME as [Phase],
(Select Name from RPT_CUSTOM_LIST_VALUES
where CUSTOM_PROPERTY_VALUE_ID = RI1.CUST_09) as [Key Milestone Name],
convert(nvarchar(10), RI1.CUST_26,103) as [Key Milestone Date], -- leave as date
convert(nvarchar(10), RI1.CUST_29,103) as [Target Completion Date], -- leave as date
RI1.SEVERITY_NAME as [Status Color],
RI1.CUST_01 as [Status Summary],
RI1.OWNER_NAME as [IT Owner],
(Select Name from RPT_CUSTOM_LIST_VALUES
where CUSTOM_PROPERTY_VALUE_ID = RI1.CUST_10) AS [Application]
from
RPT_INCIDENTS RI1
where
RI1.PROJECT_ID = 445
and RI1.IS_DELETED = 0
and (RI1.INCIDENT_STATUS_NAME <> '5.1-Cancelled' and RI1.INCIDENT_STATUS_NAME <> '5.2-Completed')
My output should be, however, the last column should have names not values. The values are from the Lookup table and I need a way to pull that data so that the values are now names.
Report Output
I can't test without your data, but hopefully it will work for you:
select RI1.incident_id as [Project Incident #]
, [Business Name] = s1.Name
,RI1.NAME as [Project Name]
,RI1.INCIDENT_STATUS_NAME as [Phase]
, [Key Milestone Name] = s2.Name
,convert(nvarchar(10), RI1.CUST_26,103) as [Key Milestone Date] -- leave as date
,convert(nvarchar(10), RI1.CUST_29,103) as [Target Completion Date] -- leave as date
,RI1.SEVERITY_NAME as [Status Color]
,RI1.CUST_01 as [Status Summary]
,RI1.OWNER_NAME as [IT Owner]
, [Application] = LEFT(s3.App,LEN(APP) - SIGN(LEN(s3.APP)))
From RPT_INCIDENTS AS RI1
OUTER APPLY (Select TOP 1 i.Name from RPT_CUSTOM_LIST_VALUES as i where i.CUSTOM_PROPERTY_VALUE_ID = RI1.CUST_02) as s1
OUTER APPLY (Select TOP 1 i.Name from RPT_CUSTOM_LIST_VALUES as i where i.CUSTOM_PROPERTY_VALUE_ID = RI1.CUST_09) as s2
OUTER APPLY (SELECT App = (
Select i.Name + ','
from RPT_CUSTOM_LIST_VALUES as i
where i.CUSTOM_PROPERTY_VALUE_ID = RI1.CUST_10
FOR XML PATH(''))
) as s3
where RI1.PROJECT_ID = 445
and RI1.IS_DELETED = 0
and (RI1.INCIDENT_STATUS_NAME <> '5.1-Cancelled' and RI1.INCIDENT_STATUS_NAME <> '5.2-Completed')
Related
I want to group by Quote ID, I am not able to get it to work though. I've been banging my head on this one for a while.
EDIT: I'm trying to group the Quantity items into one column, so for example if a Quote ID column has 3 items with the same Quote ID but different quantities, I want to display them in the same row in this fashiong - $QuoteID, $QuantityFromRow1, $QuantityFromRow2, $QuantityFromRow3.
SELECT TOP(100)
PPV8.dbo.CUSTOMER.ID As [Customer ID]
, PPV8.dbo.CUSTOMER.NAME As [Customer]
, PPV8.dbo.CUSTOMER.CITY As City, Null As [PM]
, PPV8.dbo.CUSTOMER.STATE As State
, PPV8.dbo.QUOTE_PRICE.QUOTE_ID As [Quote ID]
, FLOOR(PPV8.dbo.QUOTE_PRICE.QTY) As Quantity
, PPV8.dbo.QUOTE_LINE.PART_ID As [Part ID]
, SUBSTRING(PPV8.dbo.QUOTE_LINE.CUSTOMER_PART_ID, 6, 12) As [Style #]
, PPV8.dbo.QUOTE_LINE.DESCRIPTION As Description
, PPV8.dbo.QUOTE_PRICE.UNIT_PRICE As [Unit Price]
, PPV8.dbo.QUOTE_LINE.CREATE_DATE As [Create Date]
, PPV8.dbo.QUOTE.SALESREP_ID As [Rep]
, PPV8.dbo.QUOTE.STATUS As [Quote Status]
, PPV8.dbo.QUOTE.FOLLOWUP_DATE As [Follow Up]
, PPV8.dbo.QUOTE.EXPECTED_WIN_DATE As [Due Date]
FROM
CUSTOMER
INNER JOIN
QUOTE ON PPV8.dbo.CUSTOMER.ID = PPV8.dbo.QUOTE.CUSTOMER_ID
INNER JOIN
QUOTE_LINE ON PPV8.dbo.QUOTE.ID = PPV8.dbo.QUOTE_LINE.QUOTE_ID
INNER JOIN
QUOTE_PRICE ON PPV8.dbo.QUOTE_LINE.QUOTE_ID = PPV8.dbo.QUOTE_PRICE.QUOTE_ID
AND PPV8.dbo.QUOTE_LINE.LINE_NO = PPV8.dbo.QUOTE_PRICE.QUOTE_LINE_NO
WHERE
PPV8.dbo.QUOTE.STATUS = 'A'
AND PPV8.dbo.QUOTE.EXPECTED_WIN_DATE > '20170101'
ORDER BY
PPV8.dbo.QUOTE.EXPECTED_WIN_DATE ASC
All (non aggregate) columns in the select statement must be included in the group by clause
So you are missing the point of group by
Hello I am learning to write sql queries and I am trying to query a ledger table to SELECT a field "ENCID" where there are more than 4 distinct values in a separate file "TDATE" for each distinct ENCID.
Then filter by a 3rd field "ITEMTYPE"
This is what I have:
SELECT
[ENCID]
,[PATIENTID]
,[ITEMTYPE]
,[Service Date]
,[Transaction Date]
,[Trans]
,[PracticeName]
FROM TABLE1
WHERE ITEMTYPE = 'S'
AND ENCID IN (SELECT ENCID FROM TABLE1 WHERE Count(Distinct [Transaction Date]) >4
AND ITEMTYPE = 'S')
I am getting this error "DataSource.Error: Microsoft SQL: An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference."
Try this instead:
SELECT
[ENCID]
,[PATIENTID]
,[ITEMTYPE]
,[Service Date]
,[Transaction Date]
,[Trans]
,[PracticeName]
FROM TABLE1
WHERE ITEMTYPE = 'S'
AND ENCID IN (
SELECT ENCID
FROM TABLE1
WHERE ITEMTYPE = 'S'
GROUP BY ENCID
HAVING Count(Distinct [Transaction Date]) >4
AND MAX ([Transaction Date]) - MIN ([Transaction Date]) > 60
)
Generally, aggregate functions can only be used in SELECT, HAVING, and ORDER BY clauses (as WHERE determines exactly which records are being aggregated).
What the error message is surprisingly elaborating on is the unique cases where WHERE may contain an aggregate function. Such as this:
SELECT a.id
FROM a
GROUP BY a.id
HAVING a.id IN (
SELECT b.a_id
FROM b
WHERE b.total = COUNT(a.something)
)
For background: this works fine without the addition of the 'E' Table in production.
I am trying to execute the below query but am getting the error:
Msg 8114, Level 16, State 5, Line 10
Error converting data type varchar to numeric.
The odd thing is that it executes fine on our test DB - not seeing anything trying to convert to numeric so a bit baffled. Not really sure what would cause that difference as I assume data types are the same in the test DB and the production DB - any ideas?
Thanks.
/* - adding po balance qty causes duplicates
- adding stock category causes duplicates
- added PO comments using MAX function to return only first comment - gets rid of duplicates*/
/* Using NEW employee table as of 11/2 */
SELECT
S.team_member_name AS [ASSIGNED EMPLOYEE], --Using new employee table - only on bus unit as of 11/2
H.po_type AS [ PO TYPE],
G.order_no AS [GPS PO #],
P.po_number AS [SAP PO NUMBER],
M.department AS [DEPARTMENT],
G.order_qty AS [GPS QTY],
SUM(P.po_ordered_quantity) AS [SAP QUANTITY],
(SUM(P.po_ordered_quantity) - G.order_qty) AS [DIFFERENCE],
G.last_conf_date_cst AS [LAST CONFIRMED DATE],
K.business_unit_desc AS [BU],
M.[description] AS [DESCRIPTION],
P.material AS [MATERIAL],
MAX(P.comment) AS [PO COMMENT],
MIN(E.date) AS [FIRST SHOWN ON RPT]
FROM
(SELECT
order_no, order_qty, order_status,
last_conf_date_cst
FROM
asagdwpdx_prod.dbo.SimoxOrder1
UNION ALL
SELECT
order_no, order_qty, order_status,
last_conf_date_cst
FROM
asagdwpdx_prod.dbo.SimoxOrder2
UNION ALL
SELECT
order_no, order_qty, order_status,
last_conf_date_cst
FROM
asagdwpdx_prod.dbo.SimoxOrder3) G
JOIN
pdx_sap_user.dbo.vw_po_header H ON G.order_no = h.ahag_number
JOIN
pdx_sap_user.dbo.vw_po_item P ON H.po_number = P.po_number
JOIN
pdx_sap_user.dbo.vw_mm_material M ON P.material = M.material
JOIN
adi_user_maintained.dbo.SCM_PO_Employee_Name S ON P.po_number = S.po_number
JOIN
pdx_sap_user.dbo.vw_kd_business_unit K ON M.business_unit_code = K.business_unit_code
JOIN
adi_user_maintained.dbo.scm_po_error_tracking E ON E.po_number = P.po_number
WHERE
M.business_segment_code NOT IN ('421', '420', '422', '424') --exclude adi golf
AND E.report_source = 'gpsvssap_qty'
GROUP BY
G.order_no, -- GROUP BY needed on aggregate function in SELECT
G.order_qty,
G.order_status,
P.po_number,
P.material,
P.del_indicator,
H.po_created_by,
M.[description],
M.department,
S.team_member_name,
K.business_unit_desc,
G.last_conf_date_cst,
H.po_type
HAVING
G.order_qty <> SUM(P.po_ordered_quantity)
AND G.order_status NOT IN ('60', '90') -- excluding GPS cancelled (90) & shipped (60) - do we need to exclude other status'?
AND P.del_indicator <> 'L'
You might want to look at 'MAX(P.comment)'. You cant find Max of string. Unless your comment is numeric
I have the following code to insert data from a table in another database, but how can I insert into a primary key column by incrementing the last record in ID column value by 1? In my case [WORK ORDER #] is a primary key it doesn't allow null.
[WORK ORDER #] is nvarchar(10)
INSERT INTO DB1.dbo.WORKORDERS ([WORK ORDER #], [CUSTOMER], [SO DATE], [SO NUMBER])
SELECT *
FROM OPENQUERY([DB29],
'SELECT DISTINCT
NULL, --need to set auto increment value here
Customers.Customer_Bill_Name,
JrnlHdr.TransactionDate,
JrnlHdr.Reference)
FROM Customers
INNER JOIN JrnlHdr ON Customers.CustomerRecordNumber = JrnlHdr.CustVendId
WHERE JrnlHdr.JrnlKey_Journal = 11
AND JrnlHdr.TransactionDate = CURDATE()
-------------------// i tried as follows-----
--> You only do this one time...not with each query
create sequence dbo.WorkOrderSequence
as int
start with 43236
--> I took out the part that failed (you got option 1 and 3 kinda
--> mashed together)
insert DB1.dbo.WORKORDERS
([WORK ORDER #],[CUSTOMER],[SO DATE],[SO NUMBER],[ASSY PN-S],[CUSTOMER PN],[SHIP VIA],[PROMISED DATE],[COMMENTS],[PO #],[WO Notes])
select
convert(varchar(10), next value for DB1.dbo.WorkOrderSequence ),
x.Customer_Bill_Name,
x.TransactionDate,
x.Reference,
x.ItemID,
x.PartNumber,
x.WhichShipVia,
x.ShipByDate,
x.Comment2,
x.CustomerInvoiceNo,
x.SalesDescription
from
openquery
([DB29],
'select distinct
Customers.Customer_Bill_Name,
JrnlHdr.TransactionDate,
JrnlHdr.Reference,
LineItem.ItemID ,
LineItem.PartNumber,
Customers.WhichShipVia,
JrnlHdr.ShipByDate,
JrnlHdr.Comment2,
JrnlHdr.CustomerInvoiceNo,
LineItem.SalesDescription
FROM Customers
INNER JOIN JrnlHdr
ON Customers.CustomerRecordNumber = JrnlHdr.CustVendId
LEFT OUTER JOIN Address
ON Customers.CustomerRecordNumber = Address.CustomerRecordNumber
INNER JOIN JrnlRow
ON JrnlHdr.PostOrder = JrnlRow.PostOrder
INNER JOIN LineItem
ON JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber
WHERE JrnlHdr.JrnlKey_Journal = 11 AND JrnlHdr.TransactionDate = CURDATE()
AND JrnlHdr.PostOrder = JrnlRow.PostOrder
AND JrnlHdr.CustVendId = Customers.CustomerRecordNumber
AND JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber
AND JrnlHdr.POSOisClosed = 0'
) as x
Option 1
If you're on at least SQL Server 2012 (you didn't mention a specific version), you have a general sequence number generator that you can use. I like it a lot for this kind of scenario. In the DB1 database, you'd add your sequence like this:
create sequence dbo.WorkOrderSequence
as int
start with 5002230 --> pick a starting number greater
--> than any existing [WorkOrder #]
Then, you can just get the next number(s) in your insert-for-select statement:
insert DB1.dbo.WORKORDERS
([WORK ORDER #], [CUSTOMER], [SO DATE], [SO NUMBER])
select
convert(varchar(10), next value for DB1.dbo.WorkOrderSequence ),
x.Customer_Bill_Name,
x.TransactionDate,
x.Reference
from
openquery
([DB29],
'select distinct
Customers.Customer_Bill_Name,
JrnlHdr.TransactionDate,
JrnlHdr.Reference
from
Customers
inner join
JrnlHdr on
Customers.CustomerRecordNumber = JrnlHdr.CustVendId
where
JrnlHdr.JrnlKey_Journal = 11
and
JrnlHdr.TransactionDate = CURDATE()'
) as x
The sequence is a standalone auto-incrementing number. Every time you use the next value for dbo.WorkOrderSequence, it auto-increments. This way, you don't have to modify any table definitions.
Option 2
Alternatively, you could alter the DB1.dbo.WORKORDERS table so that the default value to use the expression...
alter table dbo.WORKORDERS
alter column [Work Order #] nvarchar(10) not null
default( convert( nvarchar(10), next value for dbo.WorkOrderSequence ) )
If you do this, then you can completely omit inserting the [Work Order #] altogether and let the default do the magic.
Option 3
If you're not on 2012, but on at least 2008, you can still get there...but it's a little trickier because you have to get the current starting [Work Order #]:
insert DB1.dbo.WORKORDERS
([WORK ORDER #], [CUSTOMER], [SO DATE], [SO NUMBER])
select
convert(varchar(10), x.RowNum + y.MaxOrderNum ),
x.Customer_Bill_Name,
x.TransactionDate,
x.Reference
from
openquery
([DB29],
'select distinct
row_number() over( order by JrnlHdr.TransactionDate ) as RowNum,
Customers.Customer_Bill_Name,
JrnlHdr.TransactionDate,
JrnlHdr.Reference
from
Customers
inner join
JrnlHdr on
Customers.CustomerRecordNumber = JrnlHdr.CustVendId
where
JrnlHdr.JrnlKey_Journal = 11
and
JrnlHdr.TransactionDate = CURDATE()'
) as x
cross join
(
select
convert( int, max( [Work Order #] ) ) as MaxOrderNum
from
Db1.dbo.WORKORDERS
) as y
Option 4
If you're on something earlier than 2008...you'll probably want a stored procedure to do the insert in two steps: inserting the work orders into a temporary table (one with an auto-increment [Work Order #] starting at the current table's max( [Work Order #] ) + 1 )...and then step 2 would insert the temp table into WORKORDERS with a convert.
I've dabbled a little with SQL but not to create tables as much. I have used postgreSQL along with knex to do so and I believe the solution that should fit for your needs as well is using the value unique. I apologize if that's not correct since I am junior to coding, but hopefully looking at this will help or looking at the SQL docs :) difference between primary key and unique key
I have a query that pulls accurate data when ran on SSMS, but when I create a report using SSRS with the exact same query, it misses out results that come from one of two temp tables I use.
DECLARE #from int --= #fromparameter
DECLARE #to int --= #toparameter
/*
For debug
*/
set #from = 0
set #to = 50
/*
================================================================================
Build a temp table with all accounts that have a move out date within params
================================================================================
*/
IF OBJECT_ID('tempdb.dbo.#tempProperty', 'U') is not null drop table #tempProperty
select
sa.spark_AccountNumber
,sa.spark_PropertyIdName
into
#tempProperty
from
SparkCRM_MSCRM.dbo.spark_account sa
where
sa.spark_AccountNumber IN (
select distinct
sa.spark_AccountNumber
--,sa.spark_TenantMoveinDate
--,sa.CreatedOn
--,DATEDIFF(day,sa.spark_TenantMoveinDate,sa.CreatedOn) as [Difference]
from
SparkCRM_MSCRM.dbo.spark_account sa
where
sa.spark_TenantMoveinDate BETWEEN dateadd(DAY,#from,getdate()) AND dateadd(DAY,#to,getdate())
)
/*
================================================================================
--create CTE with all accounts per property
================================================================================
*/
--;with RowRanked (AccountNumber,Name,Rowrank,MoveinDate,MoveOotDate,SProperty,PProperty)
--AS
--(
IF OBJECT_ID('tempdb.dbo.#temp', 'U') is not null drop table #temp
SELECT
sa.spark_AccountNumber [Account Number]
,sa.spark_name [Account Name]
,ROW_NUMBER() OVER(PARTITION BY sa.spark_PropertyIDName ORDER BY COALESCE (sa.spark_TenantMoveinDate, sa.spark_agreementdate) DESC) [rowRank]
,COALESCE (sa.spark_TenantMoveinDate, sa.spark_agreementdate) [Tenant Move In Date]
,sa.spark_TenantMoveoutDate [Tenant Move Out Date]
,sa.spark_PropertyIdName [Property ID]
,p.spark_name [Property Name]
into #temp
FROM
SparkCRM_MSCRM.dbo.spark_property p
LEFT JOIN
SparkCRM_MSCRM.dbo.spark_account sa
on sa.spark_PropertyId = p.spark_propertyId
WHERE
sa.spark_PropertyIdName IN (SELECT spark_PropertyIdName from #tempProperty)
--)
/*
================================================================================
build final dataset
================================================================================
*/
select distinct
sa.spark_AccountNumber [Account Number]
,sa.spark_name [Name]
,concat (
sa.spark_HouseNumber ,' ',
sa.spark_HouseName ,' ',
sa.spark_Address1 ,' ',
sa.spark_Address2 ,' ',
sa.spark_Address3 ,' ',
sa.spark_Address4 ,' ',
sa.spark_Postcode
) [Address]
,sa.spark_Email [Email]
,sa.spark_HomePhone [Landline]
,sa.spark_Mobile [Mobile Number]
,COALESCE(a3.Name,a2.Name,a1.Name) [Letting Agent Partner]
,sa.spark_tariffidName [Tariff]
,sa.spark_PPMTariffName [PPM Tariff]
,pm.Option_Label [Payment Method]
,sa.spark_Balance [Account Balance]
,sa.spark_IntendedMoveOut [Date of Likely Move Out]
,sa.spark_TenantMoveoutDate [Current Tenant Move Out Date]
,rr.[Account Number] [New Account Number]
,rr.[Tenant Move In Date] [New Account Move In Date]
,case
when pc.spark_CallDriver is not null
then 'Yes'
else
'No'
end [Arrangement to Pay]
,ds.Option_Label [Stops]
from
SparkCRM_MSCRM.dbo.spark_account sa
--inner join
-- DBS.dbo.Meter m
-- on m.cust_ref = sa.spark_AccountNumber collate DATABASE_default
-- and m.meter_status = 2
left join
SparkCRM_MSCRM.dbo.spark_property sp
on sp.spark_propertyid = sa.spark_propertyid
left join
SparkCRM_MSCRM.dbo.account a1 --branch
on sp.spark_PartnerId = a1.accountid
left join
SparkCRM_MSCRM.dbo.account a2 --brand
on a1.parentaccountid = a2.accountid
left join
SparkCRM_MSCRM.dbo.account a3 --partner
on a2.parentaccountid = a3.accountid
left join
SparkCRM_Custom.dbo.GetCRMOptions('spark_account', 'spark_paymentmethod') pm
ON pm.Option_Value = sa.spark_paymentmethod
left join
SparkCRM_Custom.dbo.GetCRMOptions('spark_account','spark_DebtorStatus') ds
on ds.Option_Value = sa.spark_DebtorStatus
left join
SparkCRM_MSCRM.dbo.PhoneCall pc
on pc.spark_Account = sa.spark_accountId
and pc.spark_CallDriver = 101
left join
#temp rr
on rr.[Property ID] = sa.spark_PropertyIdName
and rr.Rowrank = 1
where
coalesce(
sa.spark_IntendedMoveOut
,sa.spark_TenantMoveoutDate
)
BETWEEN
dateadd(DAY,#from,getdate()) AND dateadd(DAY,#to,getdate())
and
sa.spark_name not like '%occupier%'
This returns data when I run the query in SQL Server Management Studio, but copying it into SSRS Report Builder seems to remove any results from the #temp table. You'll notice that I was originally use a CTE for the second table, but I tried using a temp table instead in case it SSRS was struggling with CTEs.
Any help would be much appreciated!
You should avoid using #temp tables in Reporting Services, if for no other reason that it will cause all sorts of trouble if people try to run the report concurrently.
It would be better for you to instead create a Stored Procedure that your Report can call. This will allow you to apply indexes and another performance modifications as needed, and it will behave exactly the same as running the query stand-alone in SSMS