SQL Server 2012 :: Get OrderIDs That Only Match The Criteria

Aug 8, 2015

I am stuck with a query that I am working on. I have data like below.

DECLARE @Input TABLE
(
OrderID INT,
AccountID INT,
StatusID INT,
Value INT
)

INSERT INTO @Input VALUES (1,1,1,15), (2,1,1,20), (3,2,1,5), (4,2,2,40), (5,3,1,20), (6,1,2,40), (7,1,2,40)

If an Account's value reaches 20 for StatusID = 1 and 40 for StatusID = 2, that is a called "Good". I want to find out which order made the Account become "Good".

By looking at the data, it is understandble that AccountID 1 crossed Status ID 1's limit of 20 with order 2, but the status ID 2's limit was only crossed after the 6th order was placed. So my output should show 6 for AccountID 1.

For AccountID 2, value of statusID 1 was 5 with orderid 3, but it reached the limit for status id 2 of 40 with order 4. But the first condition was not met. so it shouldn't be seen in the output.

Same with AccountID 3 as well, It reached the limit of status id 1 with order 5 but the limit for order 2 wasn't reached so it should be ignored as well.

I wrote the code as below, its working fine but I still know there are better ways to write since I will be working with atleast a million records.

;WITH CTE AS
(
SELECT OrderID,AccountID, StatusID, SUM(Value) OVER(Partition By AccountID, StatusID ORDER BY OrderID) AS RunningTotal
FROM @Input

[Code] ....

View 2 Replies


ADVERTISEMENT

SQL Server 2008 :: How To Delete Tables In Database Whose Table Names Match A Criteria

Jul 22, 2015

The database has approx. 2500 temporary tables. The temp tables match a pattern such as APTMP... I tried deleting the tables in SSMS with the statement, Delete from Information_Schema.tables where substring(table_name,1,5) = 'APTMP' This returns the error message"Ad hoc updates to system catalogs are not allowed".

What is the correct way to delete a group of tables whose name match a pattern from within SSMS?

View 9 Replies View Related

SQL Server 2012 :: Adding Flags Depending On Criteria

Feb 12, 2014

I have a data output with many rows. In order to group things with flags, I do this in excel using 2 formulas which *** a flag of 0 or 1 in 2 new columns.

This takes a long long time as I have hundreds of thousands of rows and wondered of I could do it in sql?

Its transact SQL and the formulas I use in excel are:

=IF(SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2)*($C$2:$C2>=C2-1/24)*($C$2:$C2< C2+1/24))> 1,0,1)
=IF(SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2))>1,0,1)

How I can do this in sql??

The columns above do not relate to the actual columns I use, just an example.

View 9 Replies View Related

SQL Server 2012 :: SELECT Multiple Criteria If Not Null

Sep 2, 2014

I have a dataset where i want to select the records that matches my input values. But i only want to try macthing a field in my dataset aginst the input value, if the dataset value is not NULL.

I always submit all 4 input values.

@Tyreid, @CarId,@RegionId,@CarAgeGroup

So for the first record in the dataset i get a succesfull output if my input values matches RegionId and CarAgeGroup.

I cant figure out how to create the SQl script for this SELECT?

My dataset
TyreIdCarIdRegionIdCarAgeGroup
NULLNULL1084 2
65351084 1
5351084 1
NULL411085 NULL
120NULLNULL NULL
NULLNULL1084 2
65NULL1084 NULL

View 9 Replies View Related

SQL Server 2012 :: How To Match Values From A PIVOT

Jan 31, 2014

I'd like to get a extract table result, with a reference id primary key, showing the maximum dates for events and who was responsible for them. I can get the max(date) field in columns using PIVOT, but can't see a way to get the 'who' field without lots of LEFT JOINs.

Here's some test data and code which shows the principle:

CREATE TABLE #t
(
ref INT ,
id INT ,
who VARCHAR(10) ,
checkin DATE

[Code] ....

The result set is:

ref 1 who1 2 who2 3 who3 4 who4
123 2014-01-18 carol 2014-01-18 andy 2014-01-16 bill 2014-01-17 carol
456 NULL NULL 2014-01-17 NULL NULL NULL NULL NULL

Is there some way to avoid all the LEFT JOINs, maybe by using another PIVOT, to produce the same result?

View 4 Replies View Related

SQL Server 2012 :: Including Spreadsheet Data Into Exclusion Criteria?

Sep 18, 2015

I am trying to import data from 4 columns in a spreadsheet, the Columns are (Last Name - First Name - ID - Code) and this spreadsheet has around 10k records. I want to add what is in this spreadsheet to the query I have below that uses the EXCEPT operator but I am not sure the best way to go about it.

Using the example I have filtered below for the name "Denise Test", at the end of the day I want everything that is in the spreadsheet to also be excluded from the results.

So before the spreadsheet lets say the 2nd query referencing table C has the following results for Denise Test

Last_Name First_Name ID Code
Test Denise 1 5
Test Denise 2 4

After adding the spreadsheet I want it to show this:

Last_Name First_Name ID Code
Test Denise 1 5
Test Denise 2 4
Test Denise 3 3

Here is the query as it stands now without the inclusion of the spreadsheet:

SELECT
ta.last_name,
ta.first_name,
tb.ID,
tb.code
FROM
TableA ta
INNER JOIN TableB tb

[code]....

View 0 Replies View Related

SQL Server 2012 :: Match Name In Different Tables Where Name Order Is Reversed

Aug 6, 2015

CREATE TABLE #NAME1(FULLNAME VARCHAR (100))
INSERT INTO #NAME1(FULLNAME) VALUES('JOHN X. DOE')
INSERT INTO #NAME1(FULLNAME) VALUES('FITZGERALD F. SCOTT')

CREATE TABLE #NAME2(LASTNAME VARCHAR(25), MI VARCHAR(2), FIRSTNAME VARCHAR(25))
INSERT INTO #NAME2(LASTNAME, MI, FIRSTNAME) VALUES('DOE', 'X', 'JOHN')
INSERT INTO #NAME2(LASTNAME, FIRSTNAME) VALUES('FITZGERALD', 'F SCOTT')

My task is to find matches between these two tables on "name."

View 1 Replies View Related

SQL Server 2012 :: Excluding Records Whose Values From 2 Different Fields Match

Aug 31, 2015

Using MSSQL 2012

I have a simple select query and I need to eliminate records whose values from 2 different fields match. I thought I had this working, but if one of those fields in my data IS NULL it filters out those records. If I comment out my last line then my number record shows, if I include that statement that record drops. The only thing I see in my data is the Name and PName are both NULL in the data for that particular number. Just need to filter out any records where it finds those 3 Names that also have "Default" as the PName, then include everything else even if Name or Pname is NULL.

Below is my where clause.

WHERE [DETERMINATION] <> 'Denied'
AND [Number] ='A150731000039'

---- Removes incorrect records where these names match----
AND ([Name] NOT IN ('GLASSMAN','NANCY','LUDEMANN') AND [PName] = 'DEFAULT')

View 4 Replies View Related

SQL Server 2012 :: Calculate Number Of Groups And Group Size With Multiple Criteria

Jun 15, 2015

I need to calculate the last two columns (noofgrp and grpsize) No of Groups (count of Clientid) and Group Size (number of clients in each group) according to begtim and endtime. So I tried the following in the first Temp table

GrpSize= count(clientid) over (partition by begtime,endtime) else 0 end
and in the second Temp Table, I have
select
,GrpSize=sum(grpsize)
,NoofGrp=count(distinct grpsize)
From Temp1

The issue is for the date of 5/26, the begtime and endtime are not consistent. in Grp1 (group 1) all clients starts the session at 1030 and ends at 1200 (90 minutes session) except one who starts at 11 and end at 1200 (row 8). For this client since his/her endtime is the same as others, I want that client to be in the first group(Grp1). Reverse is true for the second group (Grp2). All clients begtime is 12:30 and endtime is 1400 but clientid=2 (row 9) who begtime =1230 but endtime = 1300. However, since this client begtime is the same as the rest, I wan that client to be in the second group (grp2) My partition over creates 4 groups rather than two.

View 9 Replies View Related

SQL Server 2012 :: Generate Flag To Check Whether Join Condition Match Or Not

Oct 12, 2015

I want to join 2 tables, table a and table b where b is a lookup table by left outer join. my question is how can i generate a flag that show whether match or not match the join condition ?

**The lookup table b for column id and country are always not null values, and both of them are the keys to join table a. This is because same id and country can have multiples rows in table a due to update date and posting date fields.

example table a
id country area
1 China Asia
2 Thailand Asia
3 Jamaica SouthAmerica
4 Japan Asia

example table b
id country area
1 China Asia
2 Thailand SouthEastAsia
3 Jamaica SouthAmerica
5 USA America

Expected output
id country area Match
1 China Asia Y
2 Thailand SouthEastAsia Y
3 Jamaica SouthAmerica Y
4 Japan Asia N

View 3 Replies View Related

SQL Server 2012 :: How To Match Two Different Date Columns In Same Table And Update Third Date Column

May 30, 2015

I want to compare two columns in the same table called start date and end date for one clientId.if clientId is having continuous refenceid and sartdate and enddate of reference that I don't need any caseopendate but if clientID has new reference id and it's start date is not continuous to its previous reference id then I need to set that start date as caseopendate.

I have table containing 5 columns.

caseid
referenceid
startdate
enddate
caseopendate

[code]...

View 4 Replies View Related

SQL 2012 :: Search Criteria Parameter Value

Jun 20, 2014

Say I have a query like

DECLARE @ID UNIQUEIDENTIFIER, @SOMEDATE DATE
SELECT * FROM myTable WHERE ID = @ID AND DATEFIELD=@SOMEDATE
I want to pass values to @ID and @SOMEDATE, such that it meets the WHERE criteria for all values in the respective fields.

What parameter value should I pass such that all values are selected? In the actual SP, I have uniqueidentifier, varchar and date parameters.

View 2 Replies View Related

SQL 2012 :: Limiting Query Results With 3 Criteria For Each Record

Mar 20, 2015

I am trying to write a query that gives me the personal records from speed skaters on e.g. the 500 mtrs. I do this with the query:

SELECT cdsDistance AS Distance
, prsFirstName
, prsLastName
, min(crtFinalTime) AS MinTime
FROM tb....... INNER JOIN etc..
GROUP BY cdsDistance, prsFirstName, prsLastName
ORDER BY min(crtFinalTime)

In itself this works fine. However, there are complicating factors. Sometimes a speed skater has multiple PRs, meaning the he/she has the same fastest time more than once.

If these times are achieved on multple days, the 1st date is the official PR. (meaning: "Min of racedate")
If they are raced on the same day the 1st race is the PR (meaning: "Min of distancenumber")

Changing the code to:

SELECT cdsDistance AS Distance
, prsFirstName
, prsLastName
, MIN(crtFinalTime) AS MinTime
, MIN(cdsStartDate) AS RaceDate
, MIN(cdsDistanceNumber) AS DistanceNumber

FROM tb.......
GROUP BY cdsDistance, prsFirstName, prsLastName
ORDER BY min(crtFinalTime)

This gives me the wrong outcome because it gives me the "MIN" of every field, and they are not necessarily on the same row.

An option would be to calculate min(crtFinalTime), if for a person there is more than 1 result, calculate min of date, and then (if there is still more than 1 row) min of distancenumber.

Seems complicated, and I have the feeling there must be a better way (apart from: how to get this code)

Stacking subqueries in the FROM statement seems like a option be costly (time wise). There are more than 10 million rows (and growing) to run through.

As an example a few times:

DistanceFirst nameLast name Time Date Distance nr.
500 Yuya Oikawa 34.49 201311155
500 Yuya Oikawa 34.49 201311153
500 Yuya Oikawa 34.49 201311172

Yuya has 3 best times (34.49), 15-11-2013 is the 1st date, then distance nr 3 is the 1st distance raced. Therefore the 2nd row is the only row I would like to get in my endresult.

View 4 Replies View Related

SQL 2012 :: Percentage Of Rows That Meet Multiple Criteria?

Jun 2, 2015

I am working on a project that was assigned to me that has to do with data in one of our SQL databases. I have the following query that takes information from a single table and averages test scores for each student.

--Group all scores from same student and average them together

with cte_names as
(
SELECT StudentID, MAX(StudentName) AS StudentName
FROM LDCScores
WHERE schoolYear='2014-2015' AND term = 3
GROUP BY StudentID

[code].....

I now need to take the results from the above query and determine the percentage of students, per school that scored a 2 or greater in grade 7 for each test. For grade 8 scored a 2.5 or greater, grade 9 scored a 3 or greater, grade 10 scored a 3 or greater, grade 11 scored a 3.5 or greater, and grade 12 scored a 3.5 or greater.

View 7 Replies View Related

SQL 2012 :: Design A Table To Hold Filters For Selection Criteria?

May 5, 2014

I have an ordering database with several tables that store data of orders belonging to a wide variety of clients. There is a generic report that I need to run which outputs the same data elements. However the criteria to select these orders will vary widely between each client. For e.g.

i) for client# 1 it could be all orders that are still open after 30 days of placing an order

(
OrderStatus = 'Open'
AND
GetDate() - OrderCreationDate >= 30
)

ii) for client# 2 it could be all orders that have been completed 60 days or earlier

(
OrderStatus = 'Completed'
AND
GetDate() - OrderCompletedDate >= 60
)

iii) for client# 3 it could be a combination of different things (all orders in West Region that are in hold status for more than 10 days + all orders in Eastern Region that are in shipping and are expected to be delivered in the next 2 days + all completed orders for the rest of the regions).

(
OrderRegion = 'West'
AND
OrderStatus = 'Hold'
AND
GetDate() - OrderHoldDate >= 10

[code].....

I want to have a stored procedure that selects all data and dynamically attach the where condition at the end for filtering. This way I wouldn't have to worry about any additions/changes that are made to the selection criteria. I can build an interface for admins who can use the UI to maintain the selection criteria and not worry about any code changes to accommodate it. I would like to design a table that holds this criteria. At this point in time, I am thinking of using key value pairs (Column Name, Column Value) but I am not sure how to implement multiple logical operators.

View 4 Replies View Related

SQL 2012 :: Query To Match Multiple Results And Average

Mar 3, 2014

I work for a school district and new requirement we were just given for scoring some student scores.

Everything will currently be in one table to keep track of students test scores for various things. This table will contain students information and a student will be shown more than once in the table. The Student ID is what we will key off of to find the multiple instances of the student. The table contains the following columns: studentName, StudentId, teacherName, focus1, controllingIdeas1, reading1, development1, organization1, conventions1, and contentUnderstanding1. All of the columns with a 1 at the end will be numeric values with possible decimal values.

What we need to be able to do is some how perform a search for these multiple entries of each student and when found, average the 2 scores for each 7 test categories. The result needs to be a single line for each student that gives the student name, student id, and the 7 test category averages exported to an csv file.

View 9 Replies View Related

SQL 2012 :: DQS Term Based Relations Partial Match Not Working

Feb 11, 2015

Why terms are not being corrected on a partial match? I thought this was the point of term based relation rules.

I am testing in an email address (nvarchar) field?

E.g. trying to correct @@ to @ and .con to .com (just to test)

And everything passes.

If I test with an entire value, the field is corrected.

E.g. 605688878@@qq.com corrects to 605688878@qq.com if I enter those exact values as term based relations.

View 0 Replies View Related

SQL 2012 :: Number Of Variables Declared In INTO List Must Match That Of Selected Columns

Apr 28, 2015

I am getting error [[Msg 16924, Level 16, State 1, Line 13

Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.]] when i execute below script.

Declare @mSql1 Nvarchar(MAX)
declare @dropuser int
declare @dbname Nvarchar(max)
declare @username Nvarchar(max)

DECLARE Dropuser_Cursor CURSOR FOR

[Code] ....

View 9 Replies View Related

Best Practice Question: JOIN Criteria Vs. WHERE Criteria

May 24, 2004

For example, consider the following queries:


DECLARE @SomeParam INT
SET @SomeParam = 44

SELECT *
FROM TableA A
JOIN TableB B ON A.PrimaryKeyID = B.ForeignKeyID
WHERE B.SomeParamColumn = @SomeParam

SELECT *
FROM TableA A
JOIN TableB B ON A.PrimaryKeyID = B.ForeignKeyID AND B.SomeParamColumn = @SomeParam


Both of these queries return the same result set, but the first query filters the results in the WHERE clause whereas the the second query filters the results in the JOIN criteria. Once upon a time a DBA told me that I should always use the syntax of the first query (WHERE clause). Is there any truth to this, and if so, why?

Thanks.

View 3 Replies View Related

SQL Server Sorting Criteria

May 14, 2007

Hi All,

I've read aroud the following tecqnique to parameterize the sort criteria of a stored procedure:



PROCEDURE [ParamSortProc_EXAMPLE]

...

@SortField VARCHAR(64)

AS

BEGIN

SET NOCOUNT ON

-- ....



IF @SortField NOT IN ('Field1', 'Field2', 'Field3', 'Field4')

BEGIN

SET @SortField = 'Field1' -- Default

END



SELECT

-- ...

FROM

-- ...

WHERE

-- ...

ORDER BY

CASE @SortField WHEN 'Field1' THEN T.Field1 END ASC,

CASE @SortField WHEN 'Field2' THEN T.Field2 END ASC,

CASE @SortField WHEN 'Field3' THEN T.Field3 END DESC,

CASE @SortField WHEN 'Field4' THEN T.Field4 END DESC



The point is: the sort field is choosed based on the actual value of @SortField.



Provided the source table T has specific indexes for all the 4 fields involved into the sorting operation, does the engine actually benefit from it or, instead, treat the 4 sort conditions as computed fields and so build a temporary index to face with it?



Thanx a lot for your reply.

View 3 Replies View Related

Access Query Against SQL Server Works Only Without Criteria

Jun 23, 2006

Getting a weird error while trying out a query from Access 2003 on aSQL Server 2005 table.Want to compute the amount of leave taken by an emp during the year.Since an emp might be off for half a day (forenoon or afternoon), havethe following computed field:SessionOff: ([ForenoonFlag] And [AfternoonFlag])The query works fine when there's no criterion on SessionOff.However, when I try to get the records where the SessionOff equals 0, Iget the following error:~~~~~ODBC--call failed. [Microsoft][SQL Native Client][SQL server]Incorrect syntax near the keyword 'NOT'. (#156)~~~~~I checked the SQL of the Access query, but there's no NOT anywhere init:~~~~~SELECT tblWorkDateAttendance.*FROM tblWorkDate INNER JOIN tblWorkDateAttendance ONtblWorkDate.WorkDate = tblWorkDateAttendance.WorkDateWHERE (((([ForenoonFlag] And [AfternoonFlag]))=0) AND((tblWorkDateAttendance.WorkDate)<Date()) AND((Year([tblWorkDate].[WorkDate]))=Year(Date())) AND((Weekday([tblWorkDate].[WorkDate])) Between 2 And 6) AND((tblWorkDate.HolidayFlag)=False));~~~~~What gives?

View 4 Replies View Related

Passing Like Criteria In Parameter To SQL Server Stored Procedure

Dec 13, 2006

Hello All,
 I was hoping that someone had some wise words of wisdom/experience on this.  Any assistance appreciated... feel free to direct me to a more efficient way... but I'd prefer to keep using a stored proc.
  I'm trying to pass the selected value of a dropdownlist as a stored procedure parameter but keep running into format conversion  errors but I am able to test the query successfully in the SQLDatasource.  What I would like to do is this: select * from tblPerson where lastnames Like "A%" . Where I pass the criteria after Like.   I have the values of the drop down list as "%", "A%", "B%", ....
I've been successfully configuring all of the other params, which includes another dropdown list (values bound to a lookup table also)... but am stuck on the above...
 Thank you for any assistance,
 

View 3 Replies View Related

SQL Server 2008 :: How To Hide Criteria In Search Results

May 28, 2015

Say I want to search for a range of account numbers but only which are active. After I set my field for A (active) this field shows in my results, I dont want it to.

In Access you can easily just uncheck that field in design view, but how do I do it in sql?

View 4 Replies View Related

How To Match Adp Front Version With SQL Server Database

Jul 6, 2004

I am currently designing an adp front end that links to a Sql Server database.

In terms on front end upgrade prespective i am thinking about a logon routine procedure ( which should be a vba code code that runs at startup) to check wheter the adp front end which is being used is the latest release hence compatible with the database current version.

Create and manage version number at back end level is quiet easy however to set a version number or whatever else information in the adp is somewhat a big hassle as database properties are not available from visual basic when using adp.

Was also thinking about using my xml file which holds my configuration information such as Data source - catalog but that's mean deployment of new front end must be carried out with local xml file change.

Also any manual update of information about version in xml file could allow old front end to run with database.

Please any tips and advises on how to handle this issue highly appreciated.

Regards to everybody

View 2 Replies View Related

SQL Server 2008 :: Records That Don't Match From Two Database

Sep 24, 2015

I am using the following views from two db's to find records that don't match.

My question is can I have output of fields from the second table

SELECT distinct T1.[last name],t1.[first name],ENum
FROM ECLINICIAN_Info T1
WHERE NOT EXISTS(SELECT *
FROM ACLINICIAN_Info T2
WHERE t1.Enum = t2.Anum
and t1.[last name] = t2.lname and t1.[first name] = t2.Fname)

I would like to include t2.Anum in my select ...

View 5 Replies View Related

SQL Server 2008 :: Finding Only Fields That Don't Match In Two Different Tables

Feb 12, 2015

I have two table People and Employee, both have firstname and lastname as fields

I want to display only the names that don't match on firstname and lastname

View 3 Replies View Related

Restore From Different Server - User (sid) Does Not Match Restored Db - Fix With Sp_changeobjectowner

Jul 20, 2005

This is more of a fyi than a question.After restoring a live db backup to our development server there wasan identically named login Melb02 on both the db server and in therestored db backup.However if you log in as Melb02 on the server you cannot access anyobjects owned by Melb02 on the restored db, without puttingMelb02.<object_name> in front. This would break our app so we neededa workarround.The mssql docs say that first check if the login is the owner, thendbo then deny access - something to that effect. So this wasconfusing.workarroundI think what happened was that the db restored from the live remoteserver had a different security id (sid) to the development serveralthough both users had the same name: Melb02. Thus if you log in asMelb02 you can't get access to Melb02 objects on the restored dbbecause of the different sid.we wrote a cursor that went though everything in sysobjects belongingto Melb02 and did a : sp_changeobjectowner to a new user login thatour app now happily uses.Jol.

View 1 Replies View Related

SQL Server Admin 2014 :: DNS Name Not Match Active Directory Domain Name For Reporting Services

Feb 11, 2015

I am running into a weird issue with a new SQL Reporting Services 2014 server I built. I installed SQL Reporting 2014 on Windows Server 2012 R2 and configured Kerberos, but the site is extremely slow. After some reconfiguration and log captures I have determined the issue has to do with the Kerberos setup, however I am running a similar configuration with SQL Reporting Services 2008 on Windows Server 2008 R2 and do not run into the same errors.

The error I see while using Wireshark is KRB Error: KRB5KDC_ERR_BADOPTION NT Status: STATUS_NO_MATCH. When I drill down the into the error I can see the kerberos string is testprjmnmtreports14.company.com, which is the URL we are using to access the site. I made sure to add that name as an SPN for the service account that is running SQL Reporting Services, however I still receive the error.

Then I tried configuring the site to run without a hostheader, so I accessed the site with the server name, ECTSTSQLRS5, and the site works perfectly fine, no errors are reported either. So it seems I have isolated the issue down to Kerberos but I am not sure how to resolve it. Here is some more information about my environment:

DNS/URL used: testprjmnmtreports14.company.com
Server Name (FQDN): ECTSTSQLRS5.company.int
AD Domain Name: company.int
Server Version: Windows Server 2012 R2
AD Functional Level: 2008 R2

As you can see I am trying to use a .com address but my AD domain is .int which I think is the issue, but I do not have the same problem on my other server that is running Windows Server 2008 R2. What do I need to do to allow my new site on 2012 R2 to work with this DNS Alias?

View 0 Replies View Related

SQL Server 2008 :: Length Specified In Network Packet Payload Did Not Match Number Of Bytes Read

Mar 2, 2015

Length specified in network packet payload did not match number of bytes read; the connection has been closed. Please contact the vendor of the client library. [CLIENT: xxx.xx.xxx.xx]

Client IP address is same as the server its producing the error on. I get these messages around 12pm everyday.

View 3 Replies View Related

WHERE Criteria

Nov 28, 2007

SELECT Wins, Losses, Wins/Games AS WinningPct
FROM standings
Where WinningPct > 0.5

SQL will not allow me to put a column that I created(WinningPct) as criteria for WHERE (I know this is cause Select is evaluated last)

How can I list my results according to criteria I am creating in my query?

View 9 Replies View Related

Best Searching Criteria

Sep 30, 2007

I have a table
 GO
 CREATE TABLE [dbo].[Speech] (  [SpeechId] [int] IDENTITY(1,1) NOT NULL CONSTRAINT PkSpeech_SpeechId PRIMARY KEY,  [UniqueName] [varchar](52) NOT NULL,  [NativeName] [nvarchar](52) NOT NULL,  [Place] [nvarchar](52) NOT NULL,  [Type] [smallint] NOT NULL,  [LanguageId] [char](2) NOT NULL CONSTRAINT FkSpeech_LanguageId FOREIGN KEY (LanguageId) REFERENCES Language(LanguageId) ON UPDATE CASCADE ON DELETE CASCADE,  [SpeakerId] [int] NOT NULL CONSTRAINT FkSpeech_SpeakerId FOREIGN KEY (SpeakerId) REFERENCES Speaker(SpeakerId) ON DELETE CASCADE,  [IsFavorite] [bit] NOT NULL,  [IsVisible] [bit] NOT NULL,  [CreatedDate] [datetime] NOT NULL DEFAULT GETDATE(),  [ModifiedDate] [datetime] NULL )
Now I want to search the Table Speech
Sometimes by : SpeechIdSometimes by : SpeakerIdSometimes by : LanguageIdSometimes by : SpeechId And LanguageIdSometimes by : SpeakerId And LanguageId
All can have conditions with IsVisible, IsFavorite and Type columns.
for example
I need all Speeches withany particular SpeakerId and LanguageIdwith IsVisible equals to trueand IsFvaorite No Matterand Type equals to Audio
For these type of queries I think the solution is
GO
 CREATE PROCEDURE [dbo].[sprocGetSpeech]
  @speechId int = NULL,  @uniqueName varchar(52) = NULL,  @nativeName nvarchar(52) = NULL,  @place nvarchar(52) = NULL,  @type smallint = NULL,  @languageId char(2) = NULL,  @speakerId int = NULL,  @isFavorite bit = NULL,  @isVisible bit = NULL
 AS
  SELECT   SpeechId,   UniqueName,   NativeName,   Place,   Type,   LanguageId,   SpeakerId,   IsFavorite,   IsVisible,   CreatedDate,   ModifiedDate  FROM   Speech  WHERE   SpeechId = @speechId   AND UniqueName = CASE WHEN @uniqueName IS NULL THEN [UniqueName] ELSE @uniqueName END   AND NativeName = CASE WHEN @nativeName IS NULL THEN [NativeName] ELSE @NativeName END   AND Place = CASE WHEN @place IS NULL THEN [Place] ELSE @place END   AND Type = CASE WHEN @type IS NULL THEN [Type] ELSE @type END   AND LanguageId = CASE WHEN @languageId IS NULL THEN [LanguageId] ELSE @languageId END   AND SpeakerId = CASE WHEN @speakerId IS NULL THEN [SpeakerId] ELSE @speakerId END   AND IsFavorite = CASE WHEN @isFavorite IS NULL THEN [IsFavorite] ELSE @isFavorite END   AND IsVisible = CASE WHEN @isVisible IS NULL THEN [IsVisible] ELSE @isVisible END
Can anyone tell me?
Is it right way to do?Do you have any better solution?If my solution is better then Is there any performance loss with that query?

View 1 Replies View Related

BCP With Differing Criteria

Jul 12, 2002

I am familiar and happy with using BCP to export from SQL Server to a flat file

.. 1) Is there any way to pass a parameter to the sql script file each time so that i can vary the selection critria the script file uses each time?

.. 2) Can i batch the BCP calls together so they all use this parameter with some kind of 'super' BCP cammand?

Thanks in anticipation

View 3 Replies View Related

Group By Different Criteria

Feb 2, 2015

I have a table in the following format

reporting_date interest_payment balance
200401 10 10
200402 20 15
200403 30 20
200404 40 30
200405 50 40
200406 60 50
200407 70 60

i wanted to generate an OUTPUT in the following format :

The output of the query should look like this :

reporting_date interest_payment balance
Q1 -2004 60 10
Q2 -2004 170 30
Q3 -2004 70 60
Q4 -2004 0 0

i.e i wanted to represent data by quarter and year and group by quarter and year for interest_payment column but for balance i need to pick up the value from the first reporting date in that quarter ,so as you can see q1-2004 has 10,15 and 20 but only 10 is accounted as that was the first reporting date in that quarter

I have my query working for interest payment but i am not sure how do i pickup the first reporting value for balance in a quarter

SELECT report_year as "@date",'Q'+CAST(report_quarter+1 as varchar(1)) as "@quarter", SUM(a.balance) as "@balance", SUM(a.interest_payment) as "@interest_payment"
FROM (SELECT *,
(reporting_date%100 - 1)/3 as report_quarter,
reporting_date/100 as report_year
FROM employee) a
GROUP by report_year, report_quarter
order by report_year, report_quarter

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved