Combine 2 Queries To Produce One Result Table

Jan 9, 2014

I would like to pull all the columns from a table where the date column is within 6 months from the max date (i.e. Jul, Aug, Sep, Oct, Nov, & Dec). In addition to that, I would like to pull another column -the summary column - from the same table where the date = max(date) (Dec only).

I have written 2 queries and they produce the correct data. However, I don't know how to combine them into one resultant table. I tried to do a left join and had difficulties dealing with the different where statements from the 2 queries..

Here is query #1:

select investor, full_date, month_end_summary, category, loan_count
from cust_table
where datediff(month,full_date,(select max(full_date) from cust_table)) < 6
group by investor, full_date, month_end_summary, category, loan_count
order by investor, full_date

Here is query #2:

select investor, full_date, month_end_summary
from cust_table
where datediff(month,full_date,(select max(full_date) from cust_table)) =0
order by investor, full_date

Can they be combined into one query to produce one result table??

View 3 Replies


ADVERTISEMENT

Combine Result From Diff Queries

Jun 18, 2008

I have 3 sql queries:ex:select * from table 1 where id = 2select * from table 1 where  name = 'name'select * from table 1 where date = 'date' I want to combine these three queries into one stored procedure.I am not sure how to do this.i want to display  some column data from these 3 queries on 3 table rows as:<td> colum1 </td><td> colum2 </td><td> colum3 </td>so my SP should return some datatable .any suggestiions 

View 3 Replies View Related

6 Month Gap Doesn't Produce Result

Feb 18, 2008

hi,

iam having some strange problem. iam searching for records between from date and todate. this query works well except these conditions

a) if i give input say fromdate-2/2/2007 and todate-8/2/2007, the query goes for infinite execution time(pls note the difference between twodates is less than or equal to 6 months)

b)whereas if i give fromdate-2/2/2007 and todate-10/2/2007, the query works fine.(more than 6 months interval) seems strange for me.

pls if anyone came across these kind of errors and solved pls help me.
Thanks in advance

View 19 Replies View Related

SQL Server 2014 :: Similar Queries Produce Different Output?

Sep 22, 2015

create table #t1 (id int)
create table #t2 (id int)

insert into #t1 values (1)
insert into #t1 values (2)
insert into #t1 values (3)

insert into #t2 values (1)
insert into #t2 values (2)

Run the below quires, you will get 2 different outputs.Second is the desired output. I cant find reason for query1

-- Query1

select * from #t1 a left join #t2 b on a.id = b.id and b.id is null

-- Query1

select * from #t1 a left join #t2 b on a.id = b.id where b.id is null

View 3 Replies View Related

SQL Server 2012 :: CTE To Remove Overlaps And Produce Result

Aug 7, 2014

I am having problems building a CTE. I have a table:

declare @tbl table ( ID int, S time(0), E time(0) )

with the following data:

insert@tbl ( ID, S, E )
values ( 1, '03:00', '05:00' ),
( 1, '04:00', '06:30' ),
( 1, '22:00', '23:00' ),
( 1, '23:00', '23:40' ),
( 1, '23:30', '23:45' )

I need to build a CTE that will eliminate overlaps and produce the following result:

ID S E
-- --------- ---------
1 03:00:00 06:30:00
1 22:00:00 23:45:00

View 1 Replies View Related

Combine Sql Queries

Feb 19, 2008

Hello, I have these variables on my page:
userid = "10101"
RequestHost = "example.com"
What would be the best way performace wise to first check if the userid 10101 exists in my sql server db.  If it does exist I would then need to check if "example.com" exists for the userid in the userdomains table.  If these both exist I would then like to query some additional data.  I was hoping its possible to combine this into one query somehow.  I dont think this is the best solution:
 sqlcommand.CommandText = "SELECT UserId From Users Where UserID = '10101'"
Conn.Open()
dr = sqlcommand.ExecuteReader
if dr.hasrows then
sqlcommand2.CommandText = "SELECT UserDomain From UserDomains Where UserID = 'example.com'"
dr2 = sqlcommand2.ExecuteReader
if dr2.hasrows then
sqlcommand3.CommandText = 'Select Additional Data
dr3 = sqlcommand3.ExecuteReader
'read values
conn.close
else
conn.close
'do something
end if
else
conn.close
'do something
end if  Thanks Very Much!

View 2 Replies View Related

Combine Two Queries Into One

Jun 16, 2008

I need to combine to sql queries. Separately they work fine, but I need the "total qty" from second query put into the first query

Query 1

SELECT dbo.Job.CompanyJobId, dbo.Job.Name, dbo.Region.CompanyRegionID, dbo.Job.Active,
dbo.Job.ChangeDate
FROM dbo.Job
LEFT OUTER JOIN dbo.Division ON dbo.Job.DivisionGuid = dbo.Division.DivisionGuid
LEFT OUTER JOIN dbo.Region ON dbo.Job.RegionGuid = dbo.Region.RegionGuid
LEFT OUTER JOIN dbo.JobType ON dbo.Job.JobTypeGuid = dbo.JobType.JobTypeGuid
WHERE dbo.job.CompanyJobId = 3505048
ORDER BY dbo.Job.CompanyJobId

Query 2

SELECT case dbo.SourceType.CompanySourceTypeId
when 'PR' then SUM(dbo.ProductionEvent.Quantity)
end
AS Ttl_Qty
FROM dbo.Batch INNER JOIN
dbo.Event ON dbo.Batch.BatchGuid = dbo.Event.BatchGuid INNER JOIN
dbo.Job ON dbo.Event.JobGuid = dbo.Job.JobGuid INNER JOIN
dbo.ProductionEvent ON dbo.Event.EventGuid = dbo.ProductionEvent.EventGuid INNER JOIN
dbo.Item ON dbo.Event.ItemGuid = dbo.Item.ItemGuid INNER JOIN
dbo.Source ON dbo.ProductionEvent.SourceGuid = dbo.Source.SourceGuid INNER JOIN
dbo.SourceType ON dbo.Source.SourceTypeGuid = dbo.SourceType.SourceTypeGuid LEFT OUTER JOIN
dbo.Product ON dbo.ProductionEvent.ProductGuid = dbo.Product.ProductGuid left outer join
dbo.JobNoteEvent on Event.EventGuid = dbo.JobNoteEvent.EventGuid
WHERE dbo.Job.CompanyJobId = 3505048 and dbo.SourceType.CompanySourceTypeId = 'PR'
GROUP BY dbo.SourceType.CompanySourceTypeId

I have tried this but it doe not work:

SELECT dbo.Job.CompanyJobId, dbo.Job.Name, dbo.Region.CompanyRegionID, dbo.Job.Active,
dbo.Job.ChangeDate, Ttl_Qty
FROM dbo.Job
LEFT OUTER JOIN dbo.Division ON dbo.Job.DivisionGuid = dbo.Division.DivisionGuid
LEFT OUTER JOIN dbo.Region ON dbo.Job.RegionGuid = dbo.Region.RegionGuid
LEFT OUTER JOIN dbo.JobType ON dbo.Job.JobTypeGuid = dbo.JobType.JobTypeGuid
WHERE dbo.job.CompanyJobId = 3505048 and where Ttl_Qty =

(SELECT case dbo.SourceType.CompanySourceTypeId
when 'PR' then SUM(dbo.ProductionEvent.Quantity)
end
AS Ttl_Qty
FROM dbo.Batch INNER JOIN
dbo.Event ON dbo.Batch.BatchGuid = dbo.Event.BatchGuid INNER JOIN
dbo.Job ON dbo.Event.JobGuid = dbo.Job.JobGuid INNER JOIN
dbo.ProductionEvent ON dbo.Event.EventGuid = dbo.ProductionEvent.EventGuid INNER JOIN
dbo.Item ON dbo.Event.ItemGuid = dbo.Item.ItemGuid INNER JOIN
dbo.Source ON dbo.ProductionEvent.SourceGuid = dbo.Source.SourceGuid INNER JOIN
dbo.SourceType ON dbo.Source.SourceTypeGuid = dbo.SourceType.SourceTypeGuid LEFT OUTER JOIN
dbo.Product ON dbo.ProductionEvent.ProductGuid = dbo.Product.ProductGuid left outer join
dbo.JobNoteEvent on Event.EventGuid = dbo.JobNoteEvent.EventGuid
WHERE dbo.Job.CompanyJobId = 3505048 and dbo.SourceType.CompanySourceTypeId = 'PR'
GROUP BY dbo.SourceType.CompanySourceTypeId)

ORDER BY dbo.Job.CompanyJobId

View 4 Replies View Related

Combine SQL Queries

Mar 29, 2008

Hi,

I wonder if anyone can help. All I am trying to do is combine three SQL SELECT queries into one. They are:

SELECT COUNT(ISNULL(Result, 0)) AS Win FROM Games WHERE (CurrentSeason = 'True') AND Result = 'Win'AND ([MatchType] = @MatchType)

SELECT COUNT(ISNULL(Result, 0)) AS Lose FROM Games WHERE (CurrentSeason = 'True') AND Result = 'Lose'AND ([MatchType] = @MatchType)

SELECT COUNT(ISNULL(Result, 0)) AS Draw FROM Games WHERE (CurrentSeason = 'True') AND Result = 'Draw'AND ([MatchType] = @MatchType)

As you can see they are all doing pretty much the same thing. I have experimented by using GROUP and HAVING but end up with no results. Sorry if this is obvious but I am new to SQL!

Many Thanks

View 2 Replies View Related

Combine Two Queries - Help Please

Jul 23, 2005

I have a table that has two dates in it, a date opened and a dateclosed. I would like to create one query to give me the number ofrecords that have been opened each month plus, and this is the hardpart the number of those records that have been closed each month. Ican get the result with two seperate queries but have been unable toget it combined into one query with three values for each month, i.e.,the month, the number opened and the number of those that were openedin the month that have been subsequently closed.Here's my two queries. If anyone can help I'd appreciate.SELECT COUNT(*) AS [Number Closed], LEFT(DATENAME(m, DateOpened),3) + '' + CAST(YEAR(DateOpened) AS Char(5)) AS [Month Opened]FROM tableWHERE (DateClosed IS NOT NULL)GROUP BY CONVERT(CHAR(7), DateOpened, 120), LEFT(DATENAME(m,DateOpened), 3)+ ' ' + CAST(YEAR(DateOpened) AS Char(5))ORDER BY CONVERT(CHAR(7), DateOpened, 120)SELECT COUNT(*) AS [Number Opened], LEFT(DATENAME(m, DateOpened),3) + '' + CAST(YEAR(DateOpened) AS Char(5)) AS [Month Opened]FROM tableGROUP BY CONVERT(CHAR(7), DateOpened, 120), LEFT(DATENAME(m,DateOpened), 3)+ ' ' + CAST(YEAR(DateOpened) AS Char(5))ORDER BY CONVERT(CHAR(7), DateOpened, 120)TIABill

View 2 Replies View Related

Combine 2 Queries

Jul 20, 2005

Hi,I have 2 queries that I need to join. I have the following tables:attendancelog :headeridreportmonthattlogstuds:headeridsidclass:sidclassstatusyearcodelogdatecdatemidThe result must return all the classes that appear in query2 but notin query1.I am not sure how to join the 2 queries.Help will be appreciated :-)ThanksQUERY1select sid fromattlogstuds studsinner joinattendancelog attlogon studs.headerid=attlog.headeridwhere reportmonth=10query2-- students learning excl. studs left before 1th oct.select class.SID from classleft outer JOIN ( select * from class where yearcode=26 and status=6and ( logdate <'20041001' or CDate< '20041001' )) c6 ON c6.sid = class.sid and c6.mid=class.midand c6.cdate >= class.cdatewhere class.yearcode=26 and class.status in (3,5) andclass.cdate<'20041101' and c6.sid is null

View 1 Replies View Related

Help: Need To Combine Multiple IF Queries

Apr 14, 2008

I hit a bit of a road block on a project I have been working on.  If anyone has a suggestion or a solution for how to combine my queries that use IFELSE that would be a huge help.  I noted my query below./* will remove for aspx page use */USE Database/* these params are on the page in drop down boxes*/DECLARE @ProductID int;DECLARE @BuildID int;DECLARE @StatusID int;/* static params for this sample */SET @ProductID = -1;SET @BuildID = -2SET @StatusID = -3/*the query that will build the datagrid.  currently this runs and produces three different result sets.How do I combine these statements so they produce a single set of results? */IF (@ProductID = -1) SELECT * FROM tblTestLog ELSE (SELECT * FROM tblTestLog WHERE (ProductID = @ProductID))IF (@BuildID = -2) SELECT * FROM tblTestLog ELSE (SELECT * FROM tblTestLog WHERE (BuildID = @BuildID))IF (@StatusID = -3) SELECT * FROM tblTestLog ELSE (SELECT * FROM tblTestLog WHERE (AnalystStatusID = @StatusID))

View 12 Replies View Related

Can Anyone Show Me How To Combine These Two SQL Queries Into One

Jan 29, 2004

Hello-

i have a fairly big SQL query that is used to display data into a datagrid. Each query grabs data from two seperate databases. Is there anyway to combine these queries into one so all the data appears in 1 datagrid and not 2.

here is the 1st query:

SQL = "SELECT sum(case when month(pb_report_shippers.shipper_date_time) = 1 then pb_report_shippers_lots.quantity else 0 end) as Jan ,sum(case when month(pb_report_shippers.shipper_date_time) = 2 then pb_report_shippers_lots.quantity else 0 end) as Feb ,sum(case when month(pb_report_shippers.shipper_date_time) = 3 then pb_report_shippers_lots.quantity else 0 end) as Mar ,sum(case when month(pb_report_shippers.shipper_date_time) = 4 then pb_report_shippers_lots.quantity else 0 end) as Apr ,sum(case when month(pb_report_shippers.shipper_date_time) = 5 then pb_report_shippers_lots.quantity else 0 end) as May ,sum(case when month(pb_report_shippers.shipper_date_time) = 6 then pb_report_shippers_lots.quantity else 0 end) as Jun ,sum(case when month(pb_report_shippers.shipper_date_time) = 7 then pb_report_shippers_lots.quantity else 0 end) as Jul ,sum(case when month(pb_report_shippers.shipper_date_time) = 8 then pb_report_shippers_lots.quantity else 0 end) as Aug ,sum(case when month(pb_report_shippers.shipper_date_time) = 9 then pb_report_shippers_lots.quantity else 0 end) as Sept ,sum(case when month(pb_report_shippers.shipper_date_time) = 10 then pb_report_shippers_lots.quantity else 0 end) as Oct ,sum(case when month(pb_report_shippers.shipper_date_time) = 11 then pb_report_shippers_lots.quantity else 0 end) as Nov ,sum(case when month(pb_report_shippers.shipper_date_time) = 12 then pb_report_shippers_lots.quantity else 0 end) as Dec FROM pb_customers INNER JOIN pb_jobs ON pb_customers.customer_id = pb_jobs.customer_id INNER JOIN pb_recipes_sub_recipes ON pb_jobs.recipe_id = pb_recipes_sub_recipes.recipe_id INNER JOIN pb_jobs_lots ON pb_jobs.job_id = pb_jobs_lots.job_id INNER JOIN pb_sub_recipes ON pb_recipes_sub_recipes.sub_recipe_id = pb_sub_recipes.sub_recipe_id INNER JOIN pb_report_shippers_lots ON pb_jobs_lots.intrack_lot_id = pb_report_shippers_lots.intrack_lot_id INNER JOIN pb_report_shippers ON pb_report_shippers_lots.job_id = pb_report_shippers.job_id AND pb_report_shippers_lots.shipper_id = pb_report_shippers.shipper_id WHERE pb_customers.customer_deleted <> 1 AND pb_jobs.job_deleted <> 1 AND pb_jobs_lots.lot_deleted <> 1 AND pb_report_shippers.shipper_date_time between cast('01/01/2003 00:01AM' as datetime) and cast('12/31/2003 23:59PM' as datetime)"


Here is the 2nd query:


SQL = "SELECT ISNULL(sum(case when month(nonconformance.nc_date) = 1 then nonconformance.nc_wafer_qty else 0 end),0) as Jan , ISNULL(sum(case when month(nonconformance.nc_date) = 2 then nonconformance.nc_wafer_qty else 0 end),0) as Feb ,ISNULL(sum(case when month(nonconformance.nc_date) = 3 then nonconformance.nc_wafer_qty else 0 end),0) as Mar ,ISNULL(sum(case when month(nonconformance.nc_date) = 4 then nonconformance.nc_wafer_qty else 0 end),0) as Apr , ISNULL(sum(case when month(nonconformance.nc_date) = 5 then nonconformance.nc_wafer_qty else 0 end),0) as May ,ISNULL(sum(case when month(nonconformance.nc_date) = 6 then nonconformance.nc_wafer_qty else 0 end),0) as Jun ,ISNULL(sum(case when month(nonconformance.nc_date) = 7 then nonconformance.nc_wafer_qty else 0 end),0) as Jul ,ISNULL(sum(case when month(nonconformance.nc_date) = 8 then nonconformance.nc_wafer_qty else 0 end),0) as Aug ,ISNULL(sum(case when month(nonconformance.nc_date) = 9 then nonconformance.nc_wafer_qty else 0 end),0) as Sept ,ISNULL(sum(case when month(nonconformance.nc_date) = 10 then nonconformance.nc_wafer_qty else 0 end),0) as Oct ,ISNULL(sum(case when month(nonconformance.nc_date) = 11 then nonconformance.nc_wafer_qty else 0 end),0) as Nov ,ISNULL(sum(case when month(nonconformance.nc_date) = 12 then nonconformance.nc_wafer_qty else 0 end),0) as Dec FROM nonconformance INNER JOIN nc_department on nonconformance.department_id = nc_department.department_id INNER JOIN nc_major_category ON nonconformance.major_category_id = nc_major_category.major_category_id AND nonconformance.status_id <> '5' WHERE nc_department.scrap_category = '1' AND nonconformance.nc_date between cast('01/01/2004 00:01AM' as datetime) and cast('12/31/2004 23:59PM' as datetime)"


I know there has to be someway to combine these into 1. The issue I have is they are in different databases.


ANY HELP would be appreciated.

View 2 Replies View Related

Combine Results From 2 Queries

Nov 9, 2005

I'm trying to create a list of orders in my db that has been created correctly (some orders are not dealt with correctly...) An order should go from "open -> assigned" to "assigned -> responded" status.

I got the following query:

select org.name, count(order) AS correct, NULL AS Total
from order
left join orderstatus o1 on order.id = o1.order_id
left join orderstatus o2 on order.id = o2.order_id
left join org on order.orgid on user.id
where
o1.status = 'Open -> Assigned'
and o2.status = 'Assigned -> Responded'
and o1.time_stamp < o2.time_stamp


This gives me a list of all organisations with the correct number of orders in the system...

But now I need to add the total number of tickets they got in the system. So I was thinking about a union with a query without the were constraints

UNION 'with the above query
select org.name, NULL AS correct, count(order) AS Total
from order
left join orderstatus o1 on order.id = o1.order_id
left join orderstatus o2 on order.id = o2.order_id
left join org on order.orgid on user.id

..but that gives me a list like this:

name correct total
org1 324 NULL
org1 NULL 423

How can I combine them, or maybe doing it a better way?

View 3 Replies View Related

Help: Need To Combine Multiple IF Queries

Apr 14, 2008

I hit a bit of a road block on a project I have been working on. If anyone has a suggestion or a solution for how to combine my queries that use IFELSE that would be a huge help. I noted my query below.

/* will remove for aspx page use */
USE Database

/* these params are on the page in drop down boxes*/
DECLARE @ProductID int;
DECLARE @BuildID int;
DECLARE @StatusID int;

/* static params for this sample */
SET @ProductID = -1;
SET @BuildID = -2
SET @StatusID = -3

/*
the query that will build the datagrid. currently this runs and produces three different result sets.
How do I combine these statements so they produce a single set of results?
*/

IF (@ProductID = -1) SELECT * FROM tblTestLog
ELSE (SELECT * FROM tblTestLog WHERE (ProductID = @ProductID))

IF (@BuildID = -2) SELECT * FROM tblTestLog
ELSE (SELECT * FROM tblTestLog WHERE (BuildID = @BuildID))

IF (@StatusID = -3) SELECT * FROM tblTestLog
ELSE (SELECT * FROM tblTestLog WHERE (AnalystStatusID = @StatusID))

View 15 Replies View Related

Combine Two SQL Queries With Separate Where Statements

Jun 18, 2008

I have two SQL queries that I would like to combine.  Each query is dependent on the same table, and the same rows, but they each have their own WHERE statements. I've thought about using some JOIN statements (left outer join in particular) but then I run into the problem of not having two separate tables, and don't see where I can put in two separate WHERE statements into the final query.  I've read into aliasing tables, but I'm not quite sure how that works (how to put it into code or a JOIN statement) , or if it would solve my question.  Do you have any ideas or examples of how to solve this scenario? 

View 9 Replies View Related

Combine 2 Queries In To One (joint Query)

May 3, 2007

I have these 2 queries that I need to combine into one. What is the best way of doing it? This website is made up of 293 tables so it gets confusing.


(Query 1)
SELECT category_products.category, category_products.product, category_products.position, data.base_price, data.custom_description, models.manufacturer_id, models.custom_search_text, models.name, models.image_location
FROM category_products, data, models
WHERE category_products.category = '36'
AND category_products.product = data.model_id
AND data.model_id = models.id
AND data.active = 'y'

$manufacturer_id=$data["manufacturer_id"];


(Query 2)
SELECT inventory_types.manufacturer_id, inventory_types.default_vendor_id, vendors.id, vendors.name
FROM inventory_types, vendors
WHERE inventory_types.manufacturer_id = '$manufacturer_id'
AND inventory_types.default_vendor_id = vendors.id

View 3 Replies View Related

Confused On Syntax - Combine Two Queries

Apr 3, 2008

I have two queries that I'm trying to combine, but can't figure out how to combine them ... successfully!?! The first query is pretty simple in that I'm looking at several fields from two different tables, no big deal.

The second query calculates the years, months, days between two dates that are used in the first query. I'm stumped on how to combine the queries so that they place nice with each other and return results.

Here's the first query ...
select
RTRIM(RTRIM(vpi.LastName) + ', ' + RTRIM(ISNULL(vpi.FirstName,''))) Employee,
convert(varchar,vpi.FromEffectiveDate,101) PositionStart,
convert(varchar,vpi.ToEffectiveDate,101) PositionChange,
convert(varchar,vpi.PositionStartDate,101) PositionStartDate,
vpi.PositionReason, vpi.PositionCode, vpc.PositionCodeDescription
from vhrl_positioninfo vpi
inner join position_codes vpc on vpi.PositionCode = vpc.PositionCode

Here's the second query ...
select
[Age] = convert(varchar, [Years]) + ' Years ' +
convert(varchar, [Months]) + ' Months ' +
convert(varchar, [Days]) + ' Days', *
from
(
select
[Years] = case when BirthDayThisYear <= Today
then datediff(year, BirthYearStart, CurrYearStart)
else datediff(year, BirthYearStart, CurrYearStart) - 1
end,
[Months]= case when BirthDayThisYear <= Today
then datediff(month, BirthDayThisYear, Today)
else datediff(month, BirthDayThisYear, Today) + 12
end,
[Days]= case when BirthDayThisMonth <= Today
then datediff(day, BirthDayThisMonth, Today)
else datediff(day, dateadd(month, -1, BirthDayThisMonth), Today)
end,
Birth = convert(varchar(10) ,Birth, 121),
Today = convert(varchar(10), Today, 121)
from
(
select BirthDayThisYear =
case when day(dateadd(year, datediff(year, BirthYearStart, CurrYearStart), Birth)) <> day(Birth)
then dateadd(day, 1, dateadd(year, datediff(year, BirthYearStart, CurrYearStart), Birth))
else dateadd(year, datediff(year, BirthYearStart, CurrYearStart), Birth)
end,
BirthDayThisMonth =
case when day(dateadd(month, datediff(month, BirthMonthStart, CurrMonthStart), Birth)) <> day(Birth)
then dateadd(day, 1, dateadd(month, datediff(month, BirthMonthStart, CurrMonthStart), Birth))
else dateadd(month, datediff(month, BirthMonthStart, CurrMonthStart), Birth)
end,
*
from
(
select BirthYearStart = dateadd(year, datediff(year, 0, Birth), 0),
CurrYearStart = dateadd(year, datediff(year, 0, Today), 0),
BirthMonthStart = dateadd(month, datediff(month, 0, Birth), 0),
CurrMonthStart = dateadd(month, datediff(month, 0, Today), 0),
*
from
(
select birth = convert(datetime, fromeffectivedate) ,
Today = case when convert(datetime, toeffectivedate) = '3000-01-01'
THEN convert(datetime, convert(int,getdate()))
else vpi.toeffectivedate
end

from vHRL_PositionInfo vpi inner join position_codes vpc
on vpi.PositionCode = vpc.PositionCode

) aaaa
) aaa
) aa
)a


Here's the sample data ...
vpi table ...
LastName FirstName FromEffectDate ToEffectDate PosStartDate PosReason PosCode
Doe John 2001-10-15 3000-01-01 10-15-2001 Transfer OperPack
Smith Tom 1994-11-28 2001-10-14 1994-11-28 New Hire OperDC

vpc table ...
PosCode PosDescription
OperPack Pack Line Operator
OperDC Descaler Operator

This is what the results should look like ...
John, Doe 2001-10-15 3000-01-01 10-15-2001 Transfer OperPack Pack Line Operator 6 Years 11 Months 16 Days
John, Doe 1994-11-28 2001-10-14 1994-11-28 New Hire OperDC Descaler Operator 6 Years 6 Months 19 Days

I know the date calculation piece adds 5 additional fields to the end, but they are not needed for the final report. Any help would be greatly appreciated! Thank you! Jena

View 5 Replies View Related

Transact SQL :: Max Date Combine With Two Queries

Oct 18, 2015

I have 2 tables, i need to take the max date from PAY and Combine in MEN 

MEN 
======
id  |  Fname  
========
1   |  AAA
2      |   BBB
3      |   CCC

PAY
===
id    |    Tdate
=========
1    |   01.01.2015
1    |   02.01.2015
1    |   03.01.2015
2    |   06.01.2015
3    |   09.01.2015
3    |   10.01.2015i

I need to show this:

id  |  Fname  |  Tdate
=============
1   |  AAA      |   03.01.2015
2  |  BBB      |   06.01.2015
3   |  CCC      |  10.01.2015

View 5 Replies View Related

Combine Rows In Search Result

Aug 20, 2007

In Sql Server 2005 Express I have this table:CREATE TABLE [dbo].[Sections](
    [SectionID] [int] NOT NULL,
    [DocumentNo] [smallint] NULL,
    [SequenceNo] [smallint] NULL,
    [SectionNo] [smallint] NULL,
    [DocumentTypeID] [smallint] NULL,
    [SectionText] [ntext] NULL)
 Each paragraph of text (SectionText) is in its own row
(SectionNo)  Each primary document has a DocumentTypeID of 1 with
three subdocument types (2=Index,  3=Background, 4=Report).I run this query and return a collection of single rows from various documents grouped together by DocumentNo:     SELECT *
    FROM Sections
    WHERE CONTAINS (SectionText, 'exercise')
    ORDER BY DocumentNo
For each row that contains the search term, I would like to
return the full document (all rows as parapraphs within one row of
returned data).  In other words, I want to reconstitute the full
document as it existed prior to being inserted into the database with
paragraph separation. For exampe, if the search term is in row 3
of DocumentNo=5, DocumentTypeID=2, I want to return all the rows of
that document in one block of text that retains paragraph format
(preferablly with a line break and carriage return between
paragraphs). How can this be done?

View 2 Replies View Related

Combine Sql Query Result Columns?

Jun 2, 2008

This might be a question with an extremely easy answer.. I don't know but here I go.

I want a report with lets say

|A | B | C |
----------------



I can easily figure out the sql statements to find the columns A, B and C individually but how do I combine them?

so lets say I have

select cola as A from table1 where ....

select colb as B from table2...

They are not from the same table so I cannot combine them either (I cannot do select cola, colb from table1 etc.. )

How would I do this? Am I missing something?

View 5 Replies View Related

How To Combine Result Set With Parameter Setting?

Feb 20, 2008

I have a question regarding Execute SQL Task as I combined one statement like select count(*) from destination table, and insert into error table (source count, error count, destination count) values (?,?,?).

If I use two Execute SQL Task, it should work. I was wondering that is it possible to combine select and insert into one Execute SQL Task direct input. How to approch this?

View 6 Replies View Related

Combine Delete Queries Running Separately

May 21, 2014

I have for delete queries which I run separately. Could I have a one statement to run instead.

DELETE FROM dbo.PatientHistory
FROM dbo.PatientHistory INNERJOIN TEST_PATS ON dbo.PatientHistory.PatientGuidDigest = TEST_PATS.PatientGuidDigest

DELETE FROM dbo.PostcodeScores
FROM dbo.PostcodeScores INNERJOIN TEST_PATS
ON dbo.PostcodeScores.PatientGuidDigest = TEST_PATS.PatientGuidDigest

[Code] ....

View 2 Replies View Related

Transact SQL :: Combine 3 Tables In One Search Result

Jul 1, 2015

I need a query to publish the front page of a blog.  Each blog post needs to show BlogTitle, BlogText, PublishDate, PublishBy, Primary Image and number of comments.  I would like to be able to do this in one sql statement, if possible.

 The table structure is below, you can assume the first image returned from the image table is the primary image.  

CREATE TABLE [dbo].[Blogs](
[ID] [int] IDENTITY(1,1) NOT NULL,
[BlogTitle] [nvarchar](200) NULL,
[BlogText] [nvarchar](max) NULL,
[Tags] [nvarchar](200) NULL,

[Code] ....

View 3 Replies View Related

Call Stored Procedure For Last 4 Months Then Combine Into Final Result Set Row

May 3, 2006

I want to call my stored proc for that last 4 months. Basically all I need to do is pass each month's first date and it will do the rest. Should I shove this into a UDF first? I'm not sure if I can do that. The struction is here behind my stored proc: http://www.webfound.net/storedproc.txt

EXEC IT_Get_Dashboard_Monthly '2006-05-03 12:03:43.910' <-- change to UDF or leave it? Then how can I loop and change each month to cover the last 4 months?

I also need to ensure all 4 values returned in each interation show up in one row in the final result set that is produced

View 1 Replies View Related

Analysis :: How To Use Stored Procedure In SSAS To Combine Result From More Than Two Cubes

Jul 15, 2015

I have two cube and i would like to get data from both cube and combine the results from both cubes to get final result to display result in SSRS reports like we can do in Stored procedure using temporary tables/Joins.Is there any way in SSAS to combine the data from multiple cubes? Data needs to be retrieved from the cubes based on the user inputs.

View 3 Replies View Related

Produce Data -&&> Store In Table?

Sep 4, 2007

Hi!

I'm quite new to T-SQL and is about to build a small reporting db using SQL.
Most of the data I can move with normal INSERT INTO ... SELECT, but there are some tables that I want to
produce using T-SQL. For example I want to build a Date table like..

Date
Year
Quarter
Month
WeekDay
...

With some precalculated values for each date.

I've searched the forum but have not found any information on how to produce table contents in a good manner. I would appreciate if someone would have the time to point me in the right direction. I do not want to do this by code in my application.

My first thought is to use some kind of Insert Cursor in a While loop...

Pseudo:
---------------------
declare cursor ex for 'Insert table ... '

while
begin

(produce data)
insert data
end

close cursor
---------------------

While browsing the net I've got the feeling that you use cursor less in SQL Server than in other db-engines...


Have a nice day!

View 3 Replies View Related

Different Result Same Sql Queries

Sep 26, 2006

I wrote 2 sql queries in two different ways.
The only difference in both queries are One using '=' and other one using 'in'.
All the other data is same.In my sense '=' and 'in' same
Both queries should give same result.
But one query giving different result and other query giving different result.
Is this 2 queries different??


SELECT sum(SALES_ITEM.NET_PRICE)
FROM PRODUCT_GROUP_LINK,
PRODUCT,
SALES_ITEM
WHERE (PRODUCT_GROUP_LINK.PRODUCT_CODE=PRODUCT.PRODUCT_CODE)
AND (PRODUCT_GROUP_LINK.PRODUCT_CODE=SALES_ITEM.ORIG_PRODUCT)
AND PRODUCT.STYLE_CODE='MC001'
AND (SALES_ITEM.PRICE_LIST='1FAC'
OR SALES_ITEM.PRICE_LIST='1FAW' )
AND CLASS_CODE='TYPE'
group by STYLE_CODE


SELECT sum(sales_item.net_price)
from PRODUCT,
product_group_link,
SALES_ITEM
WHERE (PRODUCT_GROUP_LINK.PRODUCT_CODE=PRODUCT.PRODUCT_CODE)
AND (PRODUCT_GROUP_LINK.PRODUCT_CODE=SALES_ITEM.ORIG_PRODUCT)
AND PRODUCT.STYLE_CODE='MC001'
AND sales_item.PRICE_LIST IN ('1FAC','1FAW')
AND CLASS_CODE='TYPE'
group by style_code

Any idea?
Thanks

View 5 Replies View Related

Comparing Result Set Values Of 2 Queries ??

Apr 20, 2004

Any assistance would be so helpful !!

We have 2 tables.. lets call them INV and COST

Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below...

ID | AMOUNT | VAT ( INV TABLE )
1 |20.125 |2.896
2 |10.524 |1.425

ID | AMOUNT | VAT ( COST TABLE )
1 |20.125 |4.821 .... different to ID 1 in INV Table
2 |10.524 |1.425

If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946)

Thats it ???

Please could someone out there offer some ideas ?

THANKS

JON

View 4 Replies View Related

Comparing Result Set Values Of 2 Queries ??

Apr 20, 2004

Any assistance would be so helpful !!

We have 2 tables.. lets call them INV and COST

Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below...

ID | AMOUNT | VAT ( INV TABLE )
1 |20.125 |2.896
2 |10.524 |1.425

ID | AMOUNT | VAT ( COST TABLE )
1 |20.125 |4.821 .... different to ID 1 in INV Table
2 |10.524 |1.425

If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946)

Thats it ???

Please could someone out there offer some ideas ?

THANKS

JON

View 1 Replies View Related

Comparing Result Set Values Of 2 Queries ??

Apr 20, 2004

Any assistance would be so helpful !!

We have 2 tables.. lets call them INV and COST

Table INV and COST have 3 related columns, namely ID,AMOUNT and VAT. As shown below...

ID | AMOUNT | VAT ( INV TABLE )
1 |20.125 |2.896
2 |10.524 |1.425

ID | AMOUNT | VAT ( COST TABLE )
1 |20.125 |4.821 .... different to ID 1 in INV Table
2 |10.524 |1.425

If you look above, I need to sum the AMOUNT and VAT columns and get a value for each ID, then compare the two tables and get the ID's that have different values...in this case I would need a result saying ID1 as the total of INV TABLE ID1 (23.021) is different to the corresponding ID1 row in COST TABLE (24.946)

Thats it ???

Please could someone out there offer some ideas ?

THANKS

JON

View 4 Replies View Related

Big Queries Return Empty Result Set

Apr 22, 2004

Hello guys,

MS SQL server 2000 behavies strange with big queries that involves relatively large number of tables:
If I just enumerate columns I want to receive, the result set is empty. Adding * to the column list without making any change to where clause seems to solve the problem but I guess it's not the best practice.
The most amazing is that this behavior is not stable, so I suppose there's something to deal with server itself, not the application.
Has anybody suffered this problem and what solution was adopted?
Thanks for any information you can provide.

View 5 Replies View Related

Analysis :: Join Result Of Two MDX Queries

May 4, 2015

Required Output

Country Category
Internet Sales Amount
Internet Order Count

[code]....

I need to perform a SQL kind of Cross join to get the Total Count as a column along side as there are .net code and json structures defined that expects output in a certain format.

View 2 Replies View Related

Combining Results Of Two Similar Queries Into One Result Set?

Mar 5, 2012

Customers order a product and enter in a source code (sourceCd). This sourceCd is tied to a marketing program. Idea being we can see that 100 customers ordered from this promo, 200 from this catalog, etc etc. The sourceCd that a customer enters is not always accurate so there is a magic process that adjusts this OrigSourceCd into a final SourceCd, that may or may not be the same.

I am trying to generate a result set of customer count by sales program based on both the original and final source code. Problem is, I have to do each query separately because in one, I have to join SourceCdKey to SourceCdKey to get the program associated with that SourceCd and in the other i have to join OrigSourceCdKey to SourceCdKey to get the program associated with the original sourceCd. There are some programs is one results set that are not in the other, and vice versa.

I'm trying to generate a list of that shows customer counts before and after for each program, some which may be null for one, but have counts for the other. I have tries creating 2 separating views and joining them but that doesn't work because it only returns the ones they have in common.

View 6 Replies View Related







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