Transact SQL :: Get Rows Not Matching Prior Year

Apr 25, 2015

We were asked to fix a query to get rows from a prior year history table that did not match to rows in the current year to show a variance from one year to the next. Rows must match on [corpnbr],[plincd],[pgrpcd] and [pitmcd].  If the combination has rows in the current and prior year ([hstyr]) then everything is fine. However, if they have rows in the prior year (e.g. [hstyr]='2014') but not in the current year (e.g. [hstyr]='2015') then they do not show in the result.  Below is how they designed the table and below that is the stored procedure to pull the records. 

CREATE TABLE [dbo].[BillingHistory](
[BillingHistoryID] [int] IDENTITY(1,1) NOT NULL,
[entity] [varchar](4) NULL,
[plincd] [varchar](3) NULL,
[pgrpcd] [varchar](4) NULL,
[pitmcd] [varchar](4) NULL,
[newplincd] [varchar](2) NULL,

[Code] ....

View 13 Replies


ADVERTISEMENT

Transact SQL :: String Function To Extract Matching Rows

Oct 6, 2015

Consider the following: I have a table, say ORDERS, with these entries -

CustID
ProductID
1       CAN
2       2
3       1,2
4       4
5       1,2,3,4,5,CAN
6       10
7       CAN
8       1,CAN

I'd like to write a script to return only those rows WHERE ProductID = CAN along with other values in the same column. In this example, I'd like to return rows 5 & 8. How can I write this in T-SQL? So, say, check if ProductID has a comma ',' value plus the 'CAN' string. If yes, then return that row. If I use the LIKE operator, it'll return rows 1,5,7, and 8.

View 12 Replies View Related

SQL 2012 :: Load Records For Prior And Current Year

Aug 3, 2015

I have some my below requirment to loading some last year and currnet year records for some ID's in my table,

We have to load the ID's that are active at the end of the year for the prior year and ID's that are active as of today for the current year.Here is the scenario when the ID is currently terminated but active at the end of the prior year and the record is not in the table.so, we didn’t load the count for the prior year

Here prior year is 2015-2015 and Current year is 2015-2016

CREATE TABLE remp_year
(ID INT,
STATUS NVARCHAR(100) NULL,
START_DATE DATE NULL,
END_DATE DATE NULL,
date_year nvarchar(10) NULL)INSERT INTO remp_year VALUES (10,'Active','2015-05-26','2015-12-31','2015-2016');

[Code] ...

Here ID 20 and 50 for terminated records is the prior year records so it should count for the last year and those are active in this year those will count for this year.

View 3 Replies View Related

Power Pivot :: Sessions Conducted In X Years Prior To Chosen Financial Year

Jun 25, 2015

I have a simple 2 column dataset representing Date of session and Client Name (Please download workbook from here - [URL] ....  The Financial Year runs from April 1 to March 31.  I want to determine the number of sessions conducted in chosen financial year - 2.  So if I select FY 2015-16 in a slicer, then, I want view the number of session conducted client wise in FY 2013-14.  This is the formula calculated field formula I have written but when I drag this in the Pivot Table, I get an error message.  In the calculated field window, when I click on Check for errors, then there are no errors at all.

=CALCULATE([Sessions conducted],DATESBETWEEN(calendar[Dates],EDATE(FIRSTDATE(calendar[Dates]),-24),EDATE(FIRSTDATE(calendar[Dates]),-12)-1))

I cannot identify my error.

View 5 Replies View Related

Very Simple Question Regarding A DATETIME Field; Select Fields Matching Month/day/year

Jan 12, 2006

Hello All,I've got a DATETIME field, and it includes hour:minutes:second data.  I want to do selects where I can simply match on the month, day and year.  For instance, something like this:SELECT * FROM QuizAttempts WHERE DateTimeTaken = '1/12/2006'And have it match anything that was taken that day, regardless of *when* it was taken.  Any suggestions?Thanks!  -Josh

View 2 Replies View Related

Transact SQL :: DATEADD - Determine Prior Month

Jul 8, 2015

My overall problem is to do some string manipulation and then DATEADD, but I still don't know why I getting what SQL is giving me.

To get the prior month, I use the following code;

SELECT
(
SELECT
RIGHT('00' + CAST(
CASE CAST(RIGHT(MAX(Eff_Period), 2) AS int) - 1
WHEN 0 THEN 12
ELSE CAST(RIGHT(MAX(Eff_Period), 2) AS int) - 1
END AS varchar(2)), 2)
)--, -- Month
--CAST(CAST(LEFT(MAX(Eff_Period), 4) AS int) - 1 AS varchar(4)) -- Year
FROM
Current_Membership;

This correctly gives me the proper month number for the prior month, in this case, '06' since the current month is '07.'
But, for debugging, I wanted to test to make sure it would properly adjust for January - '01' - by replacing MAX(Eff_Period) with '201501.'

It did. Worked fine. Then, to make really sure, I put in '201502.'

Instead of the single record of '01,' it shot out 177,209 rows of all '02's!

I put back in the MAX(Eff_Period) instead of the date string constant and, worked fine. Swapped back in the date string - boom! - 177,209 rows again.

Like I said, I can use DATEADD - Now I'm really confused. I changed the date string to '201501' just to verify before posting this, and it spit out 177,209 rows of '01's! So, to keep from altering things and to maintain the edit history, I started up another query and C&P'd everything to it. Then, on the original, I backed up to an earlier version, one that worked. That listing is the same as above, but the commented out comma in line 9 and the commented CAST in the line after it - to get the year - were uncommented.

Now, it works with both '201501' and '201502.' But, if I replace the comments, basically removing the CAST with the year, it slams back with 177,209 rows!

View 6 Replies View Related

Transact SQL :: Date Calculation - 7 Days Prior To Specified Day Of Last Week

Sep 8, 2015

I need to run a select on Mondays to pull data for 7 days prior to the Thursday of last week; i.e. Friday - Thursday inclusive.  I'm sure this is simple, but I work with dates so infrequently that I need a refressher. 

View 7 Replies View Related

SQL Server 2012 :: Find Changed Rows (and Row Prior To Changes)

Jul 22, 2014

I have a table (represented by #Events) that holds modifications made to another table. I do have some control over the table structure and indexing. I want to pull all of the change records that were made between two dates.

The tricky part is to include the previous version of each record, which will usually be found prior to the start date in question.

The code that I have provided below works. So you can use it to easily see what should be returned. But it's very slow in production.

Any better method to pull this data together?

-- Production version of this table has 4.5 million rows (roughly 1,000 rows per day)
-- Primary key is on L4Ident (clustered)
-- nonclustered index on ProcessDate, LinkRL4
DROP TABLE dbo.#Events;
DROP TABLE dbo.#Results;
CREATE TABLE dbo.#Events (
L4Ident int IDENTITY(1,1) NOT NULL,

[Code] ....

View 4 Replies View Related

Combine Matching Multiple Rows Into One Row

Jul 23, 2005

IS there a way to combine all matching rows in a table so that itoutputs as one row, for example:tblMyStuffUniqueID int IDENTITYParentID intSomeSuch nvarchar(50)SomeSuch2 nvarchar(50)Table data:UniqueID ParentID SomeSuch SomeSuch21 1 Dog Bark2 1 Cat Meow3 3 Cow Moo4 3 Horse Whinnie5 5 Pig OinkDesired query result from Query:SELECT ??? as myText from tblMyStuff WHERE ParentID = 3myText = Cow Moo, Horse WhinnieHelp is appreciated,lq

View 2 Replies View Related

Find Matching Sets Of Rows

Apr 11, 2006

Given an ID (column B), I need to find which IDs have identical data.That is, given '200', I want the desired result to be:100The idea is that the system sees that id=200 has 5 records with theindicated data in cols C and D.It should then find any other ids with the exact same data for thosecolumns.Note, in this case, both 200 and 100 have (30:1, 30:2, 30:3, 40:4,40:5) so they match. 300 and 400 should NOT be returned.Any bright ideas out there? Thanks!DECLARE @a TABLE(A int, B int, C int, D int)DECLARE @b TABLE(A int, B int, C int, D int)INSERT INTO @a (A, B, C, D) VALUES (1, 100, 30, 1)INSERT INTO @a (A, B, C, D) VALUES (2, 100, 30, 2)INSERT INTO @a (A, B, C, D) VALUES (3, 100, 30, 3)INSERT INTO @a (A, B, C, D) VALUES (4, 100, 40, 4)INSERT INTO @a (A, B, C, D) VALUES (5, 100, 40, 5)INSERT INTO @a (A, B, C, D) VALUES (6, 200, 30, 1)INSERT INTO @a (A, B, C, D) VALUES (7, 200, 30, 2)INSERT INTO @a (A, B, C, D) VALUES (8, 200, 30, 3)INSERT INTO @a (A, B, C, D) VALUES (9, 200, 40, 4)INSERT INTO @a (A, B, C, D) VALUES (10, 200, 40, 5)INSERT INTO @a (A, B, C, D) VALUES (11, 300, 30, 1)INSERT INTO @a (A, B, C, D) VALUES (12, 300, 30, 2)INSERT INTO @a (A, B, C, D) VALUES (13, 300, 40, 3)INSERT INTO @a (A, B, C, D) VALUES (14, 400, 40, 4)INSERT INTO @a (A, B, C, D) VALUES (15, 400, 40, 5)SELECT * FROM @a

View 7 Replies View Related

Sp_helprotect Error If No Matching Rows

Aug 28, 2006

Why does sp_helprotect throw an error if there are no special security permissions for a specified @username?  Why not simply return a blank resultset?  This makes the procedure a hassle to use when trying to capture results into a table as part of another stored procedure (use it for auditing).

[Edited]The same problem occurs when I execute xp_logininfo to get the list of members for a group that has no members.  Instead of just passing back some sort of status, the procedure blows up and keeps me from scripting the procedure.

Am I just missing something?

Brandon

View 5 Replies View Related

Delete Matching Rows From Target

Apr 27, 2008

Hi

I am very new to SSIS and currently was reading through various manuals but couldnt find a way to do a simple delete.

STAGE_ORDERS looks something like

order_id order_value
100 50000
300 70000
.....

Orders table looks like
order_id order_value
100 9000
200 1000
300 8000

now i want to use SSIS to delete the orders 100,300 which are present in staging table from the orders table .

How do i accomplish this task since i dont see a delete transformation.

How about updates if i want to update the order values from the staging table to the orders table what transformation can accomplish this

regards
Hrishy

View 3 Replies View Related

Transact SQL :: Lottery Winning Numbers Matching

May 6, 2015

I'm developing a Lottery system. Here are some background information:

- Total 48 numbers
- Draw 6 numbers + 1 extra number
- each Bet select 6 numbers

And the Prize:

Prize
Selected Matched
Extra number Matched

1st
6
No

2nd
5
Yes

[Code] ...

Below is my proposed table design (simplified):

Draw table
Column
Datatype

DrawDate
date
Primary Key

ResultNumber1
tinyint

[Code] ....

There will be millions of Bet for a Draw. I need to write a stored procedure to check which bets won the 1st ~ 7th prizes. How to write a query to match the bets with the draw result? The query should be run within 1 minute. And should I change my table design?

View 5 Replies View Related

Transact SQL :: Selecting First Row After Date Matching Condition?

Sep 22, 2015

I've two audit tables, AUDIT_ORDERS and AUDIT_ORDER_LINES.

The AUDIT_ORDERS has these columns: AUDIT_ID, ORDER_ID, AUDIT_DATE and other ones.

The AUDIT_ORDER_LINES has these columns: AUDIT_ID, ORDER_ID, ORDER_LINE_ID, AUDIT_DATE and other ones.

I need to join these two tables in order to select for each order line row the first order having the related audit date lower than or equal to the audit date of the related order line.

I don't want to use the TOP 1 clause or a subquery. I think to complete a such statement:

SELECT OL.Order_Line_ID, O.Order_ID, OL.Audit_Date, O.Audit_Date
FROM AUDIT_ORDER_LINES as OL INNER JOIN AUDIT_ORDERS as O
on OL.Order_ID = O.Order_ID and O.Audit_Date <= OL.Audit_Date ...

I'd like to get the first row of the Audit_Orders with audit_date <= of the audit_date of the Audit_Order_Lines table by using the join clause.

View 9 Replies View Related

Transact SQL :: Find Parts Matching In Inventory

Sep 15, 2015

We have an application where we want to check to see if the vehicle part on a job matches to our internal parts inventory (PartsInventory table) before we order it.  The problem is that sometimes the part number matches exactly and sometimes the part number has '-' or space but if those are removed, will match to our internal part number.  Below is what I have so far but it only matches exact part numbers.  One example would be if our part number was 1013738-00-C but the job (in RepairOrderLines) had a part number of 101373800C we should consider it a match.  Both PartNumbers are varchar(30). 

SELECT dbo.PartsInventory.PartNumber, dbo.PartsInventory.PartDescription, dbo.PartsInventory.VehicleMake
FROM dbo.PartsInventory INNER JOIN
dbo.RepairOrderLines ON dbo.PartsInventory.PartNumber = dbo.RepairOrderLines.PartNumber INNER JOIN
dbo.RepairOrder ON dbo.RepairOrderLines.RecordID = dbo.RepairOrder.RecordID INNER JOIN
dbo.Vehicles ON dbo.RepairOrder.VehicleID = dbo.Vehicles.VehicleID AND dbo.PartsInventory.VehicleMake = dbo.Vehicles.VehicleMake
WHERE (dbo.RepairOrderLines.RecordID = 46001)

View 3 Replies View Related

Need A Query To Return Rows Containing ALL Matching Fields

Sep 9, 2004

I have three tables X,Y,Z. Table 'Y' is having foreign key constraints on tables 'X' and 'Z' (which happen to be primary key tables).
I would like to run a query in which I can retrieve rows from Table 'X' only if the matching rows in Table 'Y' have "ALL" their matching rows available in a simple query being run on Table "Z".
The "All" part is very important.

For more clarification, let me give you an example. Table "X" is equivalent to a mathematical "Equation" table which consists of an equation made up of several "Fields". These fields are stored in Table "Z". Table "Y" contains the primary keys from Tables "X" and "Z". i.e. Table "Y" determines what fields are required for an equation to be complete.

I am having a query "Q" on Table "Z" (Fields table) which returns me a bunch of Fields. Now, on the basis of these fields, I want to retrieve only those Equations (Table "X") which have "ALL" their required Fields present in the bunch retrieved by the Query "Q".

I hope I am clear enough.
Does anyone have any solutions???

View 2 Replies View Related

How To Find Rows With Matching Numbers In One Table

Oct 19, 2007

Hello All,

I have one table that contains information about invoices.
However I need to find out if invoice numbers have been used more than once.

I've tried to join the table to itself and find matching numbers, however I can't seem to get it to work properly.

Any help will be appreciated.
Thanks,

View 7 Replies View Related

Transact SQL :: How To Join Results Of Two Queries By Matching Columns

Aug 10, 2015

I have two queries as below;

SELECT EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours
FROM dbo.tblEventStaffRequired;

and
SELECT EventID, Role, StartTime, EndTime, Hours, COUNT(ID) AS Booked
FROM tblStaffBookings
GROUP BY EventID, Role, StartTime, EndTime, Hours;

How can I join the results of the two by matching the columns EventID, Role, StartTime and EndTime in the two and have the following columns in output EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours and Booked?

View 4 Replies View Related

Delete Rows From A Table Matching A Calculated Date

Apr 15, 2008





Hello I am new to SSIS and learning as I go. Any guidance to my questions would be appreciated.

I wrote a script that takes the current date and subtracts a number of days/months from this date. I then attempted to use an SQL Task as a select with a parameter using the calculated date from the script. I was not successful in doing this. While performing searches on the WEB with the hopes of finding a solution I came upon the following text in the Microsoft forum under EXECUTE SQL TASK.

When you use an OLE DB Connection Manager, you cannot use parameterized subqueries because the Execute SQL task cannot derive parameter information through the OLE DB provider. However, you can use an expression to concatenate the parameter values into the query string and to set the SqlStatementSource property of the task.


Having come upon this statement I moved on to putting together an OLE DB SOURCE with a Flat File Destination. The SQL that I wrote is:

SELECT BP_ID, INVC_NBR, INVC_DT, BUS_ADD_DT
FROM DW.CUST_SALE_ADDR
WHERE (BUS_ADD_DT = ?)

The flat file destination was mainly used to confirm the select.

Having confirmed my select, I changed the select in the OLE DB SOURCE as follows:

DELETE FROM DW.CUST_SALE_ADDR
WHERE (BUS_ADD_DT = ?)

I also removed the Flat File Destination. Needless to say when I tried to run the package I did not get very far as a package validation error was encountered since there were no output columns.

Can you share how I should go about peforming the delete as described from the table based on a calculated date? And am I not understanding the comment regarding the SQL Statement and the use of parameters?

Thank you and God Bless.








View 9 Replies View Related

T-SQL (SS2K8) :: Outer Join Add Non Matching Rows To Each Order Group?

Mar 30, 2015

In Outer join, I would like to add the outer columns that don't exist in the right table for each order number. So currently the columns that don't exist in the right table only appear once for the entire set. How can I go about adding PCity, PState to each order group, so that PCity and PState would be added as null rows to each group of orders?

if OBJECT_ID('tempdb..#left_table') is not null
drop table #left_table;
if OBJECT_ID('tempdb..#right_table') is not null
drop table #right_table;
create table #left_table

[Code]....

View 2 Replies View Related

SQL Server 2012 :: Selecting Matching Rows Which Exist In Particular String?

Apr 3, 2015

Suppose I have string like

@strname varchar= = '3 April 15 abcd Oh rrrrrrrAAAAdd HJHJG'

and table contains two columns having rows like,

ID text
1 abcd ER
2 abcd AS
3 abcd Oh
4 xyz TR
5 azs WS
6 abcd O
7 OP trx

how can I search a ID's which are exist in my string.

result should be,

3 abcd Oh
6 abcd O

View 4 Replies View Related

SQL Server 2012 :: Select Matching Rows Which Exist In Particular String?

Apr 14, 2015

Suppose I have string like

DECLARE @strname varchar(50) = 'i_ncm_ai04';
DECLARE @SAMPLE_DATA TABLE
(
SD_ID INT NOT NULL
,SD_TEXT VARCHAR(10) NOT NULL

[Code] ......

how can I search a ID's which are exist in my string.

result should be,

3 i_ncm
8 i_ncm_a

View 2 Replies View Related

Reporting Services :: Lookup Matching Fields In Rows Of Data

Jul 16, 2015

Our division has approximately 300 employees.  We have an annual shift bid where seniority is calculated using Date of Hire.  If 2 or more employees share the same Date of Hire then we fall back to Date of Application.  Currently the SSRS report does a very simple query and shows all the employees in order of their Date of Hire.  If they match then it sorts the matching Date of Hire entries alphabetically by the employee name.  It then becomes the task of the scheduler to locatethe entries with the same Date of Hire and manually look up the employees' dates of applications then sort them accordingly and re-write the report. 

Goal:
Convert the manual process into an automatic process by modifying the current SSRS report.
Data:
The dataset is "DivDir" which contains the following fields:  "EmpName", "DofHire", & "AppDate". 

EmpName    DofHire         AppDate
Adam ......   12/2/1996      11/15/1996
Bob ..... .... 1/16/1997       12/27/1996
Charlie ....... 1/16/1997      12/12/1996
Dan ......   ... 4/11/2001     3/22/2001

In the above example I want the SSRS report to list the employees in this order:  Adam, Charlie, Bob, Dan.How do I do this programmatically using SSRS?

View 7 Replies View Related

Transact SQL :: Preserve And Return NULL For Non Matching Values From A Table Valued Function

Jun 29, 2015

I have tables and a function as representated by the code below. The names  for objects here are just for representation and not the actual names of objects. Table RDTEST may have one or multiple values for RD for each PID. So the function GIVERD will return one or multiple values of RD for each value of PID passed to it.

When I run the following query, I get the required result except the rows for CID 500 for which PID is NULL in table T1. I want the rows for CID 500 as well with PID values as NULL.

SELECT  A.CID, 
A.ANI,
A.PID,
B.RD
FROM T1 AS A CROSS APPLY GIVERD(A.PID) B

CREATE TABLE [DBO].[RDTEST](
[PID] [INT] NULL,
[RD] [INT] NULL
)

[Code] ....

View 4 Replies View Related

Group By Month And Year Transact SQL

Feb 13, 2001

I want to set up stored procedures that let me group data into months. I use the data to produce charts so I need to be able to group into month and year like '01, 2000', '02, 2000'. What is the best way to produce data grouped into month and year from a date field? Using the Month and Year functions I get data like 1,2000 and 11,2000 which don't stand up to a text sort.

View 1 Replies View Related

Transact SQL :: Get Date Of All Weekends Of The Year Without CTE

Sep 1, 2015

I want go get all weekends of the year (year dynamic) with out CTE concept, because I need to implement in 2005 version.I have googled but getting only CTE examples.

Query to get the weekends in a year.

View 3 Replies View Related

Transact SQL :: How To Get Month And Year For A Given Date

Jun 3, 2015

I have a query for which in the where clause i use where Year(openDate) = Year(GETDATE()) and Month(OpenDate) = Month(GETDATE())-1 which would give me the data i needed for this year last month. However if i run this query on Jan 2015 or Jan 2016, this query would fail.

how to modify my where clause so that it runs regardless of even if its Jan ?

View 6 Replies View Related

Transact SQL :: First Of November Previous Year

Oct 9, 2015

How I can setup the first of November of the previous year dynamically? So running now it should be 01-11-2014 but if I run in 2th of January 2016 it should be 01-11-2015.

View 17 Replies View Related

Transact SQL :: Return Date Which Is 15 Working Days Prior To Given Future Date

Oct 28, 2015

i have written a sql function which returns only number of working days (excludes holidays and Weekends)  between given StartDate  and EndDate.
                 
USE [XXX]
GO
/****** Object:  UserDefinedFunction [dbo].[CalculateNumberOFWorkDays]    Script Date: 10/28/2015 10:20:25 AM ******/
SET ANSI_NULLS ON
GO

[code]...

I need  a function or stored procedure which will return the date which is 15 working days (should exclude holidays and Weekends) prior to the given future Date? the future date should be passed as a parameter to this function or stored procedure to return the date.  Example scenario:  If i give date as  12/01/2015, my function or stored procedure should return the date which is 15 working days (should exclude holidays and Weekends) prior to the given date i.e 12/01/2015...In my application i have a table  tblMasHolidayList where all the 2015 year holidays dates and info are stored.

View 18 Replies View Related

Transact SQL :: Query To Get Last Available Data Given Month And Year?

Jul 21, 2015

I am in seach of a query where in I can provide month, year and client name and fetch last available comments from the table.

Client,Month,Year and Comments are columns in that table.

For Ex: If i pass client as A, month as 7 and year as 2015, I should get comments for client A, month July and year 2015 if available.

If data not available, it must go to June month and so on until it finds comments.Also when month is Jan, if query is going back, year also should get changed.

View 10 Replies View Related

Transact SQL :: Setting Up Period One Year Back

Oct 5, 2015

how can I dynamically set up the period between now and one year before in a query like this:

where cast(LEFT(period_start,8)as DATE)>='2014-10-01'
and cast(LEFT(period_end,8)as DATE)<='2015-09-30' and
 
Practically in the second or third of every month I need to run the period late of one year.

View 6 Replies View Related

Transact SQL :: Calculate Rolling Year Sales?

Aug 19, 2015

I have 2 tables as follows:

table A-NewParts
PartNumber
Description
LaunchDate
a123
product a
4/1/2009

[code].....

I want to get end result as sales for each new product for a rolling period from Launch date as year1 sales,year2 sales...and so on which I got through case statements.I am stuck on how to get the total Sales for all products (including new products) in the same rolling period based on the different launch dates for each new product.

PartNumber
Description
LaunchDate
Yr1 Sales
Total Yr1 Sales
Yr2 Sales
Total Yr2 Sales
a123

[code].....

View 3 Replies View Related

Transact SQL :: Display All Days Of A Given Month And Year

Oct 17, 2015

I need a simple query to display all the days of a given month and year

View 2 Replies View Related







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