I have a table with a list of payment information i have three other tables that store different types of commission rates that were active at a particular time.
Payments table – holds all payments received by customers
DirectRate table – holds the Direct rate active between start and end dates ComRate table – holds the Commission rate active between start and end dates FieldRate table – holds the Field rate active between start and end dates
Basically I am trying to get the total value of commission on all payments for all the different rates. To give you an example one payment can be of type Direct which would have to have the correct payment rate applied from the DirectRate table for the correct date range, this also applies for payments that are of type ComRate & FieldRate.
So I have the following SQL
SELECT CASE WHEN dp.ReceivedByID = 1 THEN
dp.Amount * ((Select tF.Rate From dbo.mTrackerFeeChange tF where tF.ClientID=d.ClientID and tF.ContractID=d.ContractID AND ((dp.PaymentOn >= tF.StartDate AND dp.PaymentOn <= tF.EndDate) or (dp.PaymentOn >= tF.StartDate AND tF.EndDate IS NULL)))/100)
WHEN dp.ReceivedByID = 2 THEN
dp.Amount * ((Select tD.Rate From dbo.mTrackerDirectChange tD where tD.ClientID=d.ClientID and tD.ContractID=d.ContractID AND ((dp.PaymentOn >= tD.StartDate AND dp.PaymentOn <= tD.EndDate) or (dp.PaymentOn >= tD.StartDate AND tD.EndDate IS NULL)))/100)
ELSE
dp.Amount * (((Select tF.Rate From dbo.mTrackerFeeChange tF where tF.ClientID=d.ClientID and tF.ContractID=d.ContractID AND ((dp.PaymentOn >= tF.StartDate AND dp.PaymentOn <= tF.EndDate) or (dp.PaymentOn >= tF.StartDate AND tF.EndDate IS NULL))) + (Select tFe.Rate From dbo.mTrackerFieldChange tFe where tFe.ClientID=d.ClientID and tFe.ContractID=d.ContractID AND((dp.PaymentOn >= tFe.StartDate AND dp.PaymentOn <= tFe.EndDate) or (dp.PaymentOn >= tFe.StartDate AND tFe.EndDate IS NULL))))/100)
END
From dbo.DebtPayment dp, dbo.ImportBatchItem bi, dbo.Debt d where d.DebtID=dp.DebtID AND dp.DebtID=bi.ItemID AND bi.ImportBatchID=2
I am using dp.ReceivedByID to assertain the payment type then depending upon that using the case statement to multiply the amount by the correct rate for the correct date range in the correct table. This sql works fine but it gives me a list of commision values, one for each payment. My problem is when I try to do a sum on this case statement I get an error
“Cannot perform an aggregate function on an expression containing an aggregate or a subquery�
I am new to reporter server and I am much more familar with Crystal. I am trying to write a formula/expression that is easy in crystal but can't seem to write it in Report Server.
It is a basic If Then statement that returns a value if 2 conditions are true and another value if they are false.
So
If State = 'TX'
and
City = 'Dallas'
then 1
else
0
I have been able to use the IIF expression but I can only get it to work with one variable. So, I can do
I'm in a Database class and am finding it very difficult to find any outside help. I'm sure this will appear to be very basic to those of you who work in the Database field, but your help will be greatly appreciated.
1.Write an SQL statement to show the Warehouse and average QunatityOnHand of all items stored in a warehouse managed by 'Smith'. Use a subquery.
2.Write an SQL statement to show the Warehouse and average QunatityOnHand of all items stored in a warehouse managed by 'Smith'. Use a join. This is what I came up with. Please give me some feedback:
SELECT Avg(QuantityOnHand) FROM INVENTORY WHERE WAREHOUSE IN (SELECT WAREHOUSE FROM MANAGER WHERE Manager = ‘Smith’);
What I have is a small DTS package that truncates a table then loads it from a text file. I want to enhance it by sending an e-mail with record counts to our client.
The load is pretty straight forward
delete from marketing..solicit_consumer from marketing..solicit_consumer sc join dsi_use..dnc_tmp dt on sc.consumer_no = dt.consumer_no and sc.solicit_cd = dt.solicit_cd go insert marketing..solicit_consumer select * from dsi_use..dnc_tmp go
After I have an Active X script to format an e-mail but I need the counts from the SQL statement. I have tried to use the following with no luck.
Option Explicit
Function Main() Dim oPkg, oDataPump, sSQLStatement
' Build new SQL Statement sSQLStatement = "SELECT count (*) FROM dsi_use..dnc_tmp " & _ DTSGlobalVariables("DNC_Count").Value & "'"
' Get reference to the DataPump Task Set oPkg = DTSGlobalVariables.Parent Set oDataPump = oPkg.Tasks("DTSTask_DTSDataPumpTask_1").CustomTask
' Assign SQL Statement to Source of DataPump oDataPump.SourceSQLStatement = sSQLStatement
if oDataPump.SourceSQLStatement <> 0 then FrmtEmail () Main = DTSTaskExecResult_Success else Main = DTSTaskExecResult_Failure end if
' Clean Up Set oDataPump = Nothing Set oPkg = Nothing
End Function
The actualy format of the e-mail I think will work if ony I can get the main function to work.
Right now it gives me a VB script runtime error.
Type Mismatch:'[string: "SELECT count(*) FR"]' error on line 19
Line 19 is somewhere within these lines
' Assign SQL Statement to Source of DataPump oDataPump.SourceSQLStatement = sSQLStatement
if oDataPump.SourceSQLStatement <> 0 then FrmtEmail ()
i'm passing 4 paramaters to a stored proc. based on the values of the paramaters i add conditions to my select. can som one please reviwe the proc below and tell me if my syntax is wrong or if there is another way of doing this.
Lets say that Dealers have ZipCodes, and that a Dealer can have more than one zipCode, and we want the list of dealers that have both 90210 and 90211 zip codes. BUT we don't want any dealers that have only one of the two ZipCodes in question
What I want to do is something like this
Select DealerID from DealerZips where Zip = '90210' intersection Select DealerID from DealerZips where Zip = '90211'
but I get this error msg: Line 2: Incorrect syntax near 'intersection'
The following sql is silly, but it does run without error Select DealerID from DealerZips intersection Select DealerID from DealerZips
So I am pretty sure my problem is with the Where clauses.
another question for today (maybe another silly q :P).. can somebody shorten my case statement :-
i want to have NULL for RUdf1 til RUdf10 columns and CUdf1 til CUdf10 if it follow condition "select vblablaba'
currently im doing like below, that will take 20 CASE statement in my select statement!
CASE WHEN exists (select p.picktype from tblItemPickFormat p where p.ItemClientRef=r.ItemClientRef AND (p.PickType=c.ClientUDF1) ) THEN RecvUDf1 ELSE NULL END AS RecvUDF1, --this one until 10
CASE WHEN exists (select p.picktype from tblItemPickFormat p where p.ItemClientRef=r.ItemClientRef AND (p.PickType=c.ClientUDF1) ) THEN ClientUDf1 ELSE NULL END AS ClientUDF1, --this one until 10
This query brings back 2 rows for each record, one for each case statement. How can I change this to bring in the contsupp.notes for both types of data? Or could it be fixed in the joins?
select contact1.accountno, contact1.key5 as "Ch#", contact2.uexpsort as "Sort", contact1.company as "Church", contact1.contact as "Editor", contact1.phone1 as "Phone", contact2.uemerg as "Emergency", contact1.Address1 as "Address", contact1.city as "City", contact1.state as "State", contact1.zip as "Zip", contact2.ubulletnqt as "Qty", contact2.ubullcolor as "BullColor", contact2.ubarcode as "Barcode", contact2.udelivery as "Delivery", contact2.uoutputdev as "OutputDev", contact2.utimedeliv as "Time", contact2.ucolor as "DelivColor", contact2.ucollated as "Collated", contact2.ustapled as "Stapled", case when contsupp.contsupref = 'Delivery Notes' then contsupp.notes end as "Deliverynotes", case when contsupp.contsupref = 'Cover Change Slip' then contsupp.notes end as "CoverChangeSlip"
from Contact1 inner join contact2 on Contact1.Accountno = Contact2.Accountno inner join contsupp on Contact1.Accountno=Contsupp.Accountno where contact1.key5 not like '' and contsupp.contsupref='Delivery Notes' or contsupp.contsupref ='Cover Change Slip' order by contact1.key5
I'm unable to specify multiple columns in my order by statement if i use a case statement. Does anyone know why this is, or what syntax would make this work?
Thanks
SELECT .... ORDER BY (CASE Lower(@SortExpression) WHEN 'prodname' THEN prodname, prodprice WHEN 'prodsize' THEN prodsize, prodname WHEN 'prodprice' THEN prodprice, prodname Else prodcompany, prodname END)
I know I should know the answer to this, but I just can't quite get the syntax down
Code: Select case when zipCode = '10185' Then 'Deliver' Else when zipCode = '2309' And paid = 'Yes' Then 'Deliver' Else When zipCode = '1291' And paid = 'Yes' Then 'Deliver' Else When zipCode = '88221' And paid = 'No' Then 'Hold' Else when zipCode = '34123' Then 'Deliver' End From postalDeliveryDatabase
Hi I'm not sure if I have stated my subject line correctly for what I want to achieve, but I will attempt to explain it below.
In addition to what I have in my script below, I also need to include the following clauses:
1. where TransPerPaySequence.FinancialYTDCode like '2007', and e.EmployeeStatusCode like 'CASUAL' and p.PositionGroupCode like 'AC', then instead of using the divisor of 72, it needs to be 35; and
2. where TransPerPaySequence.FinancialYTDCode like '2008', and e.EmployeeStatusCode like 'CASUAL' and p.PositionGroupCode like 'AC', then instead of using the divisor of 72 or 35, it needs to be 31.
I would really appreciate any assistance that can be provided.
Thanks
SELECT DISTINCT pc.PositionClassificationCode, pc.Description AS positionclass, pg.PositionGroupCode, pg.Description AS positiongroup, p.Description AS position, e.PreferredName + ' ' + e.LastName AS employeename, SUM(ha.Quantity) / ((CASE p2.PositionGroupCode WHEN 'AC' THEN 72 WHEN 'AL' THEN 75 WHEN 'EX' THEN 80 WHEN 'MG' THEN 80 WHEN 'SM' THEN 80 END) * (SELECT COUNT(DISTINCT PaySequence) AS Expr1 FROM TransPerPaySequence WHERE (PayPeriodCode LIKE 'EIT') AND (Closed = '1') AND (Description LIKE 'St%'))) AS FTE, (SELECT COUNT(DISTINCT PaySequence) AS Expr1 FROM TransPerPaySequence AS TransPerPaySequence_1 WHERE (PayPeriodCode LIKE 'EIT') AND (Closed = '1') AND (Description LIKE 'St%')) AS payseq FROM HistoricalAllowance AS ha LEFT OUTER JOIN Position AS p ON ha.PositionCode = p.PositionCode LEFT OUTER JOIN PositionGroup AS pg ON p.PositionGroupCode = pg.PositionGroupCode LEFT OUTER JOIN PositionClassification AS pc ON p.PositionClassificationCode = pc.PositionClassificationCode LEFT OUTER JOIN WAP ON ha.WAPCode = WAP.WAPCode LEFT OUTER JOIN Employee AS e ON ha.EmployeeCode = e.EmployeeCode LEFT OUTER JOIN Position AS p2 ON e.PositionCode = p2.PositionCode LEFT OUTER JOIN TransPerPaySequence AS tpps ON ha.PaySequence = tpps.PaySequence WHERE (e.EmployeeCode IN ('83', '739')) AND (ha.AllowanceCode IN ('005', '201', '203', '101')) AND (tpps.FinancialYTDCode LIKE '2007%') GROUP BY pc.PositionClassificationCode, pg.PositionGroupCode, pc.Description, pg.Description, p.Description, e.PreferredName, e.LastName, p2.PositionGroupCode
So I'm thinking if I can have multiple statements within the CASE-THEN..or do I have to CASE out each individually? Kind of like this....
CASE WHEN [AddressType] = 'M' THEN [MailingAddress].[Address1] [MailingAddress].[Address2] [MailingAddress].[City] [MailingAddress].[State] [MailingAddress].[Zipcode] WHEN [AddressType] = 'D' THEN [DefaultAddress].[Address1] [DefaultAddress].[Address2] [DefaultAddress].[City] [DefaultAddress].[State] [DefaultAddress].[Zipcode]
The other table stores the priority order of the charge codes
TABLE3
CHGCODE PRIORITY DESCRPTN ACF 1 Court fee ALT 2 Late fee ANS 3 NSF fee ARC 4 Rent ADR 5 Repair AUR 6 Utility
While the forth stores the customer data:
TABLE4
NAMEID RMPROPID FIRSTNAME LASTNAME NAMEGROUP 000001234 A0A01 Jane Doe 000001234 000001235 A0A00 John White 000001235 000001236 A0A02 John Smith 000001236 000001237 A0A02 Jennifer Smith 000001236
This table's importance comes by the inclusion of the NAMEGROUP. This way if an account has multiple NAMEIDs, it can be kept straight by their shared NAMEGROUP.
I am trying to create a report using queries that will:
A) calculate the sum of the OPENAMT per NAMEGROUP per DISTINCT CHGCODE B) count the number of records (DISTINCT CHGCODEs) per DISTINCT NAMEID in ORDER by the CHGCODE PRIORITY Then C) calculate a case query whereas:
CASE WHERE TABLE1.TRANAMT=> the calculated sum of the highest priority CHGCODE THEN 'TABLE1.TRANAMT' ELSE WHERE TABLE1.TRANAMT <= the calculated sum of the highest priority CHGCODE THEN 'the calculated sum of the highest priority CHGCODE' ...then... CASE WHERE
I have a query with huge number of case statements. Basically I need to short this query with getting rid of these hundreds of CASE statements.
Because of the nature of the application I am not allowed to use a function, and just wondering if there is a possible way to rewrite this with COALESCE().
SELECT CASE WHEN A.[COL_1] LIKE '%cricket%' THEN 'ck' + ',' ELSE '' END + CASE WHEN A.[COL_1] LIKE '%soccer%' THEN 'sc' + ',' ELSE '' END + .... CASE WHEN A.[RESIUTIL_DESC] LIKE '%base%ball' THEN 'BB' + ',' ELSE '' END FROM TableName A
I have created an SQL server table in the past on a server that was all case sensative. Over time I found out that switching to a server that is not case sensative still caused my data to become case sensative. I read an article that said you should rebuild your master database then re-create your tables. So after rebuilding the master database, a basic restore would not be sufficient? I would have to go and manually re-create every single table again?
Can someone point me to a tutorial on how to search against a SQL Server 2000 using a case insensitive search when SQL Server 2000 is a case sensitive installation?
We need to install CI database on CS server, and there are some issueswith stored procedures.Database works and have CI collation (Polish_CI_AS). Server hascoresponding CS collation (Polish_CS_AS). Most queries and proceduresworks but some does not :-(We have table Customer which contains field CustomerID.Query "SELECT CUSTOMERID FROM CUSTOMER" works OK regardless ofcharacter case (we have table Customer not CUSTOMER)Following TSQL generate error message that must declare variable @id(in lowercase)DECLARE @ID INT (here @ID in uppercase)SELECT @id=CustomerID FROM Customer WHERE .... (here @id in lowercase)I know @ID is not equal to @id in CS, but database is CI and tablenames Customer and CUSTOMER both works. This does not work forvariables.I suppose it is tempdb collation problem (CS like a server collationis). I tried a property "Identifier Case Sensitivity" for myconnection, but it is read only and have value 8 (Mixed) by default -this is OK I think.DO I MISS SOMETHING ????
I am working in a SQL server database that is configured to be case-insensetive but I would like to override that for a specific query. How can I make my query case-sensitive with respect to comparison operations?
I am curious with using replication in sql server 2005 one way from db A (source) replicating to db B(destination) in which db A has a collation of CS and db B has a collation of CI. Will there be any problems with this scenario? Thanks in advance!
I have a view where I'm using a series of conditions within a CASE statement to determine a numeric shipment status for a given row. In addition, I need to bring back the corresponding status text for that shipment status code.
Previously, I had been duplicating the CASE logic for both columns, like so:
Code Block...beginning of SQL view... shipment_status = CASE [logic for condition 1] THEN 1 WHEN [logic for condition 2] THEN 2 WHEN [logic for condition 3] THEN 3 WHEN [logic for condition 4] THEN 4 ELSE 0 END, shipment_status_text = CASE [logic for condition 1] THEN 'Condition 1 text' WHEN [logic for condition 2] THEN 'Condition 2 text' WHEN [logic for condition 3] THEN 'Condition 3 text' WHEN [logic for condition 4] THEN 'Condition 4 text' ELSE 'Error' END, ...remainder of SQL view...
This works, but the logic for each of the case conditions is rather long. I'd like to move away from this for easier code management, plus I imagine that this isn't the best performance-wise.
This is what I'd like to do:
Code Block ...beginning of SQL view... shipment_status = CASE [logic for condition 1] THEN 1 WHEN [logic for condition 2] THEN 2 WHEN [logic for condition 3] THEN 3 WHEN [logic for condition 4] THEN 4 ELSE 0 END,
shipment_status_text =
CASE shipment_status
WHEN 1 THEN 'Condition 1 text'
WHEN 2 THEN 'Condition 2 text'
WHEN 3 THEN 'Condition 3 text'
WHEN 4 THEN 'Condition 4 text'
ELSE 'Error'
END, ...remainder of SQL view...
This runs as a query, however all of the rows now should "Error" as the value for shipment_status_text.
Is what I'm trying to do even currently possible in T-SQL? If not, do you have any other suggestions for how I can accomplish the same result?
I am working on a C#/asp.net web application. The application has a text box that allows a user to enter a name. The name is then saved to the database. Before the name is saved to the database, I need to be able to check if the name already exists in the database. The problem here is that what if the name is in the database as "JoE ScMedLap" and somoene enters the name as "Joe Schmedlap" which already exists in the database,but just differs in case. In other words how do deal with case sensitiviy issues.
Yesterday I received a response to my CI/CS Collation problem and therecommendation was to try and restore a CI Collation database to a CSCollation database. After creating a blank CS database a full restore(Force restore over existing database) does change the Collation toCI. I'm unsure as to how I can restore without changing theCollation. Any suggestions?
I am facing a problem in writing the stored procedure for multiple search criteria.
I am trying to write the query in the Procedure as follows
Select * from Car where Price=@Price1 or Price=@price2 or Price=@price=3 and where Manufacture=@Manufacture1 or Manufacture=@Manufacture2 or Manufacture=@Manufacture3 and where Model=@Model1 or Model=@Model2 or Model=@Model3 and where City=@City1 or City=@City2 or City=@City3
I am Not sure of the query but am trying to get the list of cars that are to be filtered based on the user input.