Creating Unions In TSQL

Aug 11, 2004

Hi everyone. I was wondering if I could get some pointers in creating a union between two tables. This is the sproc I currently have:








CREATE Procedure spGetReturnCheckForCriteria





@SearchCriteria VARCHAR(8000),





@SortOrder VARCHAR(8000),





@PageSize INT





AS





-- Declare vars





DECLARE @SQLStatement NVARCHAR(4000)





DECLARE @bldSQLStatement VARCHAR(8000)





DECLARE @retValue INT





-- Initialize vars





SET @SQLStatement = ''





SET @bldSQLStatement = ''





SET @retValue = -1





-- Sanity Check(s)





IF (@PageSize IS NULL OR @PageSize < 1)





-- Paging Size can not be Null, nor less than One





BEGIN





SET @RetValue = -30 -- "Must have a valid Paging Size for pagination: Error (-30)





RETURN





END





-- Build the Paging SQL Statement





SET @bldSQLStatement = 'SELECT TOP '





-- Add the Page Size





SET @bldSQLStatement = @bldSQLStatement + CAST(@PageSize AS VARCHAR)





-- Add Columns/Tables/Relationships





SET @bldSQLStatement = @bldSQLStatement + '





ReturnCheck.ReturnCheckID AS ReturnCheckID,


ReturnCheck.FiscalNumber AS FiscalNumber,


ReturnCheck.ReturnedDate AS ReturnedDate,


ReturnCheck.CheckNumber AS CheckNumber,


ReturnCheck.AssessPenaltyIndicator AS AssessPenaltyIndicator,


ReturnCheck.ReturnCheckCollectionStatusCode AS ReturnCheckCollectionStatusCode,


ReturnCheck.ReturnCheckReasonCode AS ReturnCheckReasonCode,


ReturnCheck.CentralCollectionsID AS CentralCollectionsReferralNumber,


TaxPayment.PaymentID AS PaymentID,


TaxPayment.DocumentLocatorNumber AS DocumentLocatorNumber,


TaxPayment.PaymentEffectiveDate AS PaymentEffectiveDate,


TaxPayment.PaymentAmount AS PaymentAmount,


TaxPayment.PaymentQuarter AS PaymentQuarter,


TaxPayment.PaymentYear AS PaymentYear,


TaxPayment.InternalReferenceNumber AS InternalReferenceNumber,


TaxPayment.PaymentTypeCode AS PaymentTypeCode,


TaxPayment.PaymentOriginCode AS PaymentOriginCode,


TaxPayment.VoucherNumber AS VoucherNumber,


TaxPayment.ReversedIndicator AS ReversedIndicator,


TaxPayment.PaymentDate AS PaymentDate,


CAST(NULL AS DATETIME) AS CCReferralDate,


DistributionPoint.UIDPrime AS UIDPrime,


DistributionPoint.UIDCheck AS UIDCheck,


DistributionPoint.UIDDistPoint AS UIDDistPoint,





CASE





WHEN ReturnCheck.UpdatedDate IS NULL THEN ReturnCheck.CreatedDate





ELSE ReturnCheck.UpdatedDate





END AS ReturnCheckTimeStamp





FROM TaxPayment





INNER JOIN DistributionPoint





ON (TaxPayment.DistributionPointID = DistributionPoint.DistributionPointID)





INNER JOIN ReturnCheck





ON (TaxPayment.PaymentID = ReturnCheck.PaymentID)





'





-- Add Search Criteria





If (@SearchCriteria IS NOT NULL)





SET @bldSQLStatement = @bldSQLStatement + ' WHERE ' + @SearchCriteria





-- Add Sort Order





IF (@SortOrder IS NOT NULL)





SET @bldSQLStatement = @bldSQLStatement + ' ' + @SortOrder





-- Set the SQLStatement





SET @SQLStatement = @bldSQLStatement


-- Execute the Paging Query


EXECUTE @retValue = sp_executeSQL @SQLStatement


GO








Look at the SQL build where I'm doing an INNER JOIN between TaxPayment and RefundCheck. Instead of this INNER JOIN, I'd like to do a union instead. If I can get any help on this I'd greatly appreciate it. Cheers.

View 3 Replies


ADVERTISEMENT

Multiple Unions Where There Are No Results In First Set Causes All Following Unions To Return Nothing.

Mar 21, 2008



I have two tables one with current data and a second with the same design that holds purged history.

I was going to create view and then jsut use a where clause to filter both tables but I figured it would be faster if the where clause was passed into each query as opposed to the whoel view having to load and then be filtered.

Select PatientName, MemberId
FROM CLAIMS
WHERE MemberID = @MemberID
UNION
Select PatientName, MemberId
FROM CLAIMSHistory
WHERE MemberID = @MemberID

But it appears that if there are no records in the first statement that the whole thing fails. I tried the union all operator with out any luck either.

Now if had a view like this;
Create view vAllClaims as
Select PatientName, MemberId
FROM CLAIMS
UNION
Select PatientName, MemberId
FROM CLAIMSHistory


And said select * from vAllClaims where memberid = 12345 would the query optimizer put the build the where statement onto each subquery or pull all the data first and query it?

View 4 Replies View Related

Creating A Common Table Expression--temporary Table--using TSQL???

Jul 23, 2005

Using SQL against a DB2 table the 'with' key word is used todynamically create a temporary table with an SQL statement that isretained for the duration of that SQL statement.What is the equivalent to the SQL 'with' using TSQL? If there is notone, what is the TSQL solution to creating a temporary table that isassociated with an SQL statement? Examples would be appreciated.Thank you!!

View 11 Replies View Related

How Many Unions?

Jul 18, 2000

I know the answer must be somewhere, but for the moment every place I look ...

How many tables can be unioned together (I think I remember that 6.5 had a limit of 16) in SQL7?

Thanks,
Judith

View 2 Replies View Related

Groupby Unions

May 6, 2004

hi
I have MSSQL query that performs multiple UNION ,but I would like to perform a GROUPBY on the whole result set.
How Can i do this?
plz help...
bono

View 4 Replies View Related

Syntax Error With Unions?

Oct 2, 2001

I doing a union of two select queries, and I keep getting
the following error:

syntax error converting the nvarchar value 'foo' to a column of data type int.

I've tried using CAST and CONVERT in the select statement, but it doesn't change the outcome.

The table it's complaining about (the one containing the value 'foo'), is of data type nVarChar, so I don't have any idea why SQL server would try to convert it to an integer.

Is this a common problem? I'd love to know what I'm doing wrong.

View 1 Replies View Related

Syntax Error With Unions?

Oct 2, 2001

I doing a union of two select queries, and I keep getting
the following error:

syntax error converting the nvarchar value 'foo' to a column of data type int.

I've tried using CAST and CONVERT in the select statement, but it doesn't change the outcome.

The table it's complaining about (the one containing the value 'foo'), is of data type nVarChar, so I don't have any idea why SQL server would try to convert it to an integer.

Is this a common problem? I'd love to know what I'm doing wrong.

View 1 Replies View Related

Ordering In Conjunction With Unions

Oct 7, 2004

Why does this not work? When I run this query in Query Analyzer, I get the error "Incorrect syntax near the keyword 'UNION'." This seems simple enough...


SELECT * FROM SalesLead WHERE Age = '50' ORDER BY FirstName

UNION ALL

SELECT * FROM SalesLead WHERE Age = '60' ORDER BY FirstName


Thanks for any advice

Aaron

View 4 Replies View Related

Performance Issue With Unions In Sp's?

Jul 20, 2007

I was having a chat with a chap over lunch today and he asked if I knew of any performance issues when doing unions in stored procedures. I couldn't think of anything but he seemed sure there was.

Is there such an issue I've missed?

Mike

View 6 Replies View Related

Doing Unions With Uneven Column Amounts

Mar 14, 2006

I'm creating a program that allows users to submit a report on equipment at regular intervals. If a piece of equipment has a problem, it is given a job entry that refers back to the report for various information.

However, there will be times when a problem is noticed, and someone wants to submit it immediately; these are made into extra jobs.

To this end, I have three tables:
Reports
Jobs
ExtraJobs

Because ExtraJobs cannot be associated with a report, they have their own table, which holds information that would otherwise be grabbed from both Reports and Jobs. While there are seperate submission forms for regular jobs and extra jobs, I would like them to appear on the same query result when a user looks at submitted jobs or reports.

What I'm currently trying to do is this:
Code:

SELECT*
FROMReports LEFT JOIN Jobs
ON Reports.reportID = Jobs.reportID
UNION ALL
SELECT ExtraJobs.*
FROM ExtraJobs


This won't work because the first half of the union has an extra column (reportID) that the second half does not. Is there any way to add in a value for that non-existant column (say, ExtraJobs.reportID = -1) to make sure that both sides have an equal number of columns?

If worst comes to worst, I could add a reportID column to ExtraJobs and have it set to -1 for everything, but I'd like to keep from adding fat, if at all possible.

View 2 Replies View Related

Unions Two Tables Into A Temp Table

Aug 31, 2007

How do I do this? I have two queries that create temp tables. I need to union them together and create one temp table. Anyone done this with success?

View 4 Replies View Related

Way To Group / Count Multiple Unions Together?

Dec 9, 2013

I have 4 archive tables and 1 active table that are created the same, but contain different data based on the date. I need to get results that have three columns: AuthorName, Month, Total. This is currently working, but through my research I can't find how to start going about dealing with the fact that each Author has some of his results from one month in one table and some in another table and how to add those together into one row. Example:

(What I'm Getting)
AuthorName Month Total
Test, Fred 3 43
Test, Fred 3 12
Test, Fred 2 56
Test, Fred 5 35

[code]....

View 4 Replies View Related

View That Unions Two Other Views Does Not Work

May 1, 2006

I created a view V1 that uses an outer join with a table and calls a sub-view VS1 (ds_proj_report_date) which uses an inner join) and does an inner join with VS1. I also created another view V2 that uses inner join but does not call the sub-view VS1.

When I run the two views as below it works fine

Select * from V1
Union
Select * from V2


I then created another view V3 of the above union as

Create view V3
As
Select * from V1
Union
Select * from V2

Now when I run select * from V3, I get the following error.
Joined tables cannot be specified in a query containing outer join operators. View or function 'ds_proj_report_date' contains joined tables

View 1 Replies View Related

SQL Server 2012 :: Using Unions To Write Out Each Select Query As Distinct Line In Output

Aug 20, 2015

Basically I'm running a number of selects, using unions to write out each select query as a distinct line in the output. Each line needs to be multiplied by -1 in order to create an offset balance (yes this is balance sheet related stuff) for each line. Each select will have a different piece of criteria.

Although I have it working, I'm thinking there's a much better or cleaner way to do it (I use the word better loosely)

Example:
SELECT 'Asset', 'House', TotalPrice * -1
FROM Accounts
WHERE AvgAmount > 0
UNION
SELECT 'Balance', 'Cover', TotalPrice
FROM Accounts
WHERE AvgAmount > 0

What gets messy here is having to write a similar set of queries where the amount is < 0 or = 0

I'm thinking something along the lines of building a table function contains all the descriptive text returning the relative values based on the AvgAmount I pass to it.

View 6 Replies View Related

Equivalent Tsql For Sql Server 2000 Is Needed [from Sql Server 2005 Only Tsql]

Nov 19, 2007

Can anyone please give me the equivalent tsql for sql server 2000 for the following two queries which works fine in sql server 2005

1
-- Full Table Structure

select t.object_id, t.name as 'tablename', c.name as 'columnname', y.name as 'typename', case y.namewhen 'varchar' then convert(varchar, c.max_length)when 'decimal' then convert(varchar, c.precision) + ', ' + convert(varchar, c.scale)else ''end attrib,y.*from sys.tables t, sys.columns c, sys.types ywhere t.object_id = c.object_idand t.name not in ('sysdiagrams')and c.system_type_id = y.system_type_idand c.system_type_id = y.user_type_idorder by t.name, c.column_id


2
-- PK and Index
select t.name as 'tablename', i.name as 'indexname', c.name as 'columnname' , i.is_unique, i.is_primary_key, ic.is_descending_keyfrom sys.indexes i, sys.tables t, sys.index_columns ic, sys.columns cwhere t.object_id = i.object_idand t.object_id = ic.object_idand t.object_id = c.object_idand i.index_id = ic.index_idand c.column_id = ic.column_idand t.name not in ('sysdiagrams')order by t.name, i.index_id, ic.index_column_id

This sql is extracting some sort of the information about the structure of the sql server database[2005]
I need a sql whihc will return the same result for sql server 2000

View 1 Replies View Related

Join First Query With A Query That Contains Unions

Jun 10, 2013

I have to queries I need to combine with a left join and I am having trouble figuring out the syntax. I need to join the first query with a query that contains Unions. The queries need to by joined on File_NBR which is contained in vw_SBC_Employee_Info, vw_ADPFile and SBC_Best_Scores.

Query 1
SELECT
e1.File_NBR,
e1.Division,
e1.Department,
e1.Program,
e1.UNIT,
(e6.Mngr_FName + ' ' + e6.Mngr_LName) AS President,

[Code] .....

Query 2
SELECT
'Skill Rating' as Assessment_Type,
bs.File_NBR as ID,
bs.Skill_NBR,
bs.Best_Score as Score,
bs.Assesment_RND

[Code] .....

View 9 Replies View Related

Creating Trigger On Creating Table

Jan 28, 2008



Hi,

If I want to automatically insert a record which has default value in a table,
how can I create the trigger?

View 5 Replies View Related

TSQL Or SQL CLR?

Aug 9, 2006

Hello Friends,    I am not sure if this is the right place to post this question but if not please suggest me when it can be posted.
I have been thinking of writing Stored procs in SQL CLR/ changing all of my Stored Procs to SQL CLR.
Is there any thing that I need to keep in mind about the size of the sotred proc (like calculation intensive) before I do that? I mean can even change a TSQL stored proc which is  relatively small Stored Proc, that simply said Select * from Customers to SQL CLR? or the SQL CLR does only useful/makes difference with calculation intensive stored procs and big stored procs?
When I talked to our Architects they said every small sized stored proc can be written using SQL CLR and more over forget about the classic TSQL stored procs and get used to write SQL CLR when ever writing any database related stuff.
And also there are so many articles that discussed about the advantages of SQL CLR over the TSQL but I would appreciate if some one could put few bulletted points why do you think SQL CLR is more powerful.
Please advise.Thanks in advance,-L

View 2 Replies View Related

TSQL Please Help

Jan 8, 2006

Hi
I am creating some dynamic sql by passing variouse parametrs to my Stored Procedure.  One of my Parameters is string has lots of values seperated by a comma to help build an 'IN' statement.
SET @SQL = 'SELECT * FROM areas'SET @p1 = '10,20'If @p1 IS NOT NULLBEGINSET @sSQL = @sSQL + ' WHERE (Areas IN (''' + Replace(@p1,',',''',''') + '''))'END
The above query runs perfecly well in Query Analyser, however when I put it into my ASP.NET application I get an error of "Error converting data type varchar to numeric."
So I think I need to do some sort of casting or Converting but im not sure how to do it.  Or do I need to use a INSTRING?
I did manage to work out a method by using the follwoing
SELECT * FROM Areas WHERE PATINDEX('%,' + CAST(ArType AS VARCHAR) + ',%',',' + @p1 + ',') > 0
But I cant seem to convert the above line into coherent dynamic statement.  My feeble attempt is below but I keep getting errors
SET @sql = @sql + ' WHERE PATINDEX(''%,'' + CAST(ArType AS VARCHAR) + '',%'','','' + @p1 + '','') > 0'
IM strugging to understand all the '''. My TSQL is pretty basic, any help would be much appreciated
Many thanks in advance
 

View 1 Replies View Related

Tsql Help!

Mar 14, 2001

simple update, I want to update max_seq with max(0rdr_seq) from another table.
how do you?

update h
set max_seq = d.max(ordr_seq)
from h_drug_stage_dup h
join drug_ordr_stage d
on h.patkey = d.patkey and
h.ordr_dtm= d.ordr_dtm and
h.h_drug = d.h_Drug

View 1 Replies View Related

TSQL Help !

Jun 5, 2001

Please see below ( in my sub-query I need to say settle_date = post_date +
3 business days )
How would this be done ? Pleas help !!!

declare @PD datetime, @MY_SD datetime
--SELECT @PD = SELECT POST_DATE FROM TRANSACTION_HISTORY
--select @MY_SD = @PD + 3 --T+3
--select @MY_SD = @MY_SD + case datepart(dw, @MY_SD) when 7 then 2 when 1 then 1 else 0 end*/
SELECT
WIRE_ORDER_NUMBER FROM TRANSACTION_HISTORY
WHERE POST_DATE BETWEEN '02/01/2001' AND '02/28/2001' AND
WIRE_ORDER_NUMBER IN
(
SELECT ORDER_NUMBER
FROM TRANSACTION_ARCHIVE WHERE TRANSACTION_ARCHIVE.ORDER_NUMBER = TRANSACTION_HISTORY.WIRE_ORDER_NUMBER
SETTLE_DATE = DATEADD(day, 3, POST_DATE ) case datepart(dw, POST_DATE) when 7 then 2 when 1 then 1 else 0 end))

View 5 Replies View Related

Tsql

Oct 1, 2001

Sql Server 7.0
==============
Hi all!
To find out the duplicate entries in a particular column,
I used the following tsql

select pno ,count(pno) from table1 group by pno
having count(pno)>1

But now I have another case where i have to test duplicity as a combination of 3 columns.
ie, for Eg :I have 3 columns with the following values.

colA colB colC
1 2 3===============row 1
1 3 5===============row 2
1 2 3===============row 3
1 4 5===============row 4
8 9 0===============row 5

I want to pick up all the duplicate rows(combo of colA,colB,colC)
duplicate rows here would be row 1 and row 3.

Can somebody give me a clue as to how to achieve this via TSQL.
Any help greatly appreciated.

TIA
Kinnu

View 1 Replies View Related

TSQL

Oct 1, 2001

HI,
I am creating a stored procedure where i need to update a table.
I have a field which has year as 2000-2001 i need to remove -2001
and just store it as 2000.I created a Procedure but i am getting an
error.

create PROCEDURE prdUpdate_Year
@year varchar(40)
As
@year = Mid(Newfiels,1,4)
UPDATE AddressBook SET AddressBook.Year = @year;
GO

Thanks

View 2 Replies View Related

TSQL Help

Jun 5, 2000

Hi,

I am trying to break up a column "name" into 2 columns "first name" and "last name". The name colum is currently "lastname, firstname". Is there an easy way to do this in SQL 6.5?

I successfully extracted the first name using:

firstname = rtrim(substring(name, (charindex(',', name)), 25))

But I am having trouble doing the lastname. Please help.

Thanks so much!
Laura

View 3 Replies View Related

Tsql Help

Dec 6, 2000

Hi,

I want to write a query which selects ind and
clcode where
ind(individual) has taken all 3 classes(clcode) 15, 16 and 17.
for example: it should only return data for ind 1 from the following data as only ind 1 has taken all three classes.
How can I write it?

table: ind_history

ind clcode
----------- -----------
1 16
1 17
2 17
1 15
2 16
3 11
4 15

View 1 Replies View Related

TSQL Help

Aug 4, 2004

I need help with a query that I want to incorporate into a scheduled DTS within SQL Server 2000. I have a process that brings in records from an Excel file, compares that day's records with any related information already stored in the database, then saves a table of joined records. This leaves me with any matches to the data. I need to filter out all but the most current record, which would be identified by a column named [DATE]. Ex:

Table tblMatchedRecords

M BLah Blah2 [DATE]
1 this that 20040101
2 this them 20040102
3 this that 20040630

In this example, I would like to have the record with [DATE] = 20040630 kept, and the others deleted. All columns do not always have to match exactly. I want to be able to specify which fields that need to match and pull only the latest date.

Make sense? Can anyone offer any suggestions?

View 4 Replies View Related

Tsql Help

May 9, 2007

I have a few variables declared

@amount=100000 (any big int)
@pamount=100000
@a1,@a2 - thorugh @25 -- each a bigint
@p1,@p2,@p3
@id - int

if @id is an odd number I need to randomly change @amount-@a1 (randomly to @a1 - @a25 so it ends up being any of 25 values)
and then @pamount randomly= to either @p1,@p2 or @p3


Can someone help me do the sql for this?
it will be within my stored procedure

View 5 Replies View Related

SP Or TSQL

Nov 30, 2007

Hi
Is there any sp or command to deactivate and activate all constraints in a database...


Thanks in Advance

RKNAIR

View 6 Replies View Related

Tsql Help

Mar 4, 2008

I have 2 sql server that are registered and linked.

If I have a table in server 1 that I want to make a backup of to server 2, how would I do that in t-sqlv(if the table did not already exisit on the second server)

Thanks

"Impossible is Nothing"

View 4 Replies View Related

TSQL Help

Aug 22, 2005

A stored procedure was running slowly so I took the code, removed thesubselect and included a join, then took the max and included as partof a correlated subquery.The result is below, however, this is no improvement over the original.An advice would be greatly appreciated.SELECT FSALT.FUNDING_LINE_TYPE_ID,A.PAYMENT_PERIOD_ID,A.CASH AS CASH,A.VOLUME AS VOLUMEFROM ACTUALS AINNER JOIN (SELECT MAX(COLLECTION_PAYMENT_PERIOD_*ID) AS CPP FROMACTUALS ACT WHERE COLLECTION_PAYMENT_PERIOD_ID<=*456) AS O ON O.CPP =A.COLLECTION_PAYMENT_PERIOD_IDINNER JOIN FS_ACTUAL_LINE_TYPES FSALT ON FSALT.FS_ACTUAL_LINE_TYPE_ID =A.FS_ACTUAL_LINE_TYPE_IDINNER JOIN PAYMENT_PERIODS PP ON PP.PAYMENT_PERIOD_ID =A.PAYMENT_PERIOD_IDWHEREA.ORG_ID=24771AND A.LSC_ORG_ID=5816AND PP.FUNDING_STREAM_ID=5AND PP.FUNDING_PERIOD_ID=6GROUP BYFSALT.FUNDING_LINE_TYPE_ID,A.PAYMENT_PERIOD_ID, A.CASH, A.VOLUME

View 2 Replies View Related

How Can This Be Done Using TSQL?

Feb 22, 2008

I have a table that has a datetime field that needs a calculated time difference created when querying the table. I'm new to TSQL and I've been banging my head on this one. There is a time window that must be dealt with as well, so that any time that falls outside if the time window gets assigned a zero value (not calculated). The last record inside the window and the first record inside the window get calculated based on a given start and end time. The time outside the window is 7PM to 7AM. Here's an example:




in/outside window Time Value Calculation Time Diff (in minutes)
inside window time1 = '13:15:00' null the first record is always null
inside window time2 = '14:15:00' time2-time1 60
inside window time3 = '18:50:00' time3-time2 275
outside window time4 = '19:10:00' 18:59:59 - time3 10
outside window time5 = '21:00:00' 0 0
outside window time6 = '06:30:00' 0 0
outsidw window time7 = '06:45:00' 0 0
inside window time8 = '07:45:00' time8 - 07:00:00 15


How can this be done using TSQL? Let me know if more info is needed. Thanks!

View 8 Replies View Related

TSQL - Using WHERE

Dec 25, 2007

Hi guys,
The query below is running ok.


Code Block
USE test2006mdt

if object_id('AuxTable20071224132300') is not null exec('DROP TABLE AuxTable20071224132300')

SELECT DISTINCT
Stock.ACCOUNTKEY AS 'Stock.ACCOUNTKEY',
Stock.DOCNUMBER AS 'Stock.DOCNUMBER',
Stock.DOCUMENTID AS 'Stock.DOCUMENTID',
CASE WHEN Cast(Stock.DOCUMENTID as int) In ('1','35') THEN 'IN# ' + Cast(Stock.DOCNUMBER as varchar) WHEN Cast(Stock.DOCUMENTID as int) In ('3','120') THEN 'CM# ' + Cast(Stock.DOCNUMBER as varchar) ELSE '' END AS 'Invoice #',
Stock.VALUEDATE AS 'Stock.VALUEDATE',
Stock.TFTAL AS 'Stock.TFTAL',
Stock.CURRENCY AS 'Stock.CURRENCY',
CASE WHEN ReceiptJurnalMatch.SUF Is NULL THEN '0' ELSE -1 * ReceiptJurnalMatch.SUF END AS 'ReceiptJurnalMatch.SUF',
Stock.ID AS 'Stock.ID',
CASE WHEN ReceiptJurnalMatch.FULLMATCH Is NULL THEN '0' ELSE ReceiptJurnalMatch.FULLMATCH END AS 'ReceiptJurnalMatch.FULLMATCH'

INTO AuxTable20071224132300
FROM
RECEIPTJURNALMATCH
RIGHT OUTER JOIN JURNALTRANSMOVES ON RECEIPTJURNALMATCH.JURNALTRANSID = JURNALTRANSMOVES.ID
RIGHT OUTER JOIN STOCK
INNER JOIN ACCOUNTS ON STOCK.ACCOUNTKEY = ACCOUNTS.ACCOUNTKEY
INNER JOIN JURNALTRANS ON STOCK.ID = JURNALTRANS.STOCKID ON JURNALTRANSMOVES.TRANSID = JURNALTRANS.TRANSID
LEFT OUTER JOIN STOCKMOVES ON STOCK.ID = STOCKMOVES.STOCKID

WHERE
Stock.ACCOUNTKEY Between 'Account01' AND 'Account01'
AND Stock.Status Not In ('0','2')
AND Stock.DOCUMENTID In ('1','35','3','120')
ORDER BY Stock.ACCOUNTKEY

SELECT DISTINCT
[Stock.ACCOUNTKEY] AS 'Stock.ACCOUNTKEY',
[Stock.DOCNUMBER] AS 'Stock.DOCNUMBER',
[Stock.DOCUMENTID] AS 'Stock.DOCUMENTID',
[Invoice #] AS 'Invoice #',
[Stock.VALUEDATE] AS 'Stock.VALUEDATE',
[Stock.TFTAL] AS 'Stock.TFTAL',
[Stock.CURRENCY] AS 'Stock.CURRENCY',
Sum([ReceiptJurnalMatch.SUF]) AS 'Sum([ReceiptJurnalMatch.SUF])',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) <= 30 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '1-30',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) BETWEEN 31 AND 60 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '31-60',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) BETWEEN 61 AND 90 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '61-90',
CASE WHEN CAST(DATEDIFF(dd,[Stock.VALUEDATE],GETDATE()) AS int) > 90 THEN [Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) ELSE '' END AS '>> 90',
[Stock.TFTAL] - Sum([ReceiptJurnalMatch.SUF]) AS 'Balance'

FROM AuxTable20071224132300

WHERE Balance <> 0 ==> Getting ERROR!!!

GROUP BY [Stock.ACCOUNTKEY], [Stock.DOCNUMBER], [Stock.DOCUMENTID], [Invoice #], [Stock.VALUEDATE], [Stock.CURRENCY], [Stock.TFTAL]
The results are:

ACCOUNTKEY DOCNUMBER DOCUMENTID Invoice # VALUEDATE TFTAL CURRENCY SUF 1-30 31-60 61-90 >> 90 Balance

Account01 16917 35 IN# 16917 2007-12-25 00:00:00.000 15000 Euro 15000 0 0 0 0 0

Account01 16918 35 IN# 16918 2007-12-25 00:00:00.000 300 Euro 300 0 0 0 0 0

Account01 16919 35 IN# 16919 2007-12-25 00:00:00.000 110 Euro 110 0 0 0 0 0

Account01 16920 35 IN# 16920 2007-11-10 00:00:00.000 5 Euro 5 0 0 0 0 0

I inted to add a WHERE clause in order to Show Only Invoices with Balance <> 0, but getting Error.
Thanks in advance for any help.
Note: I am working under SQL SERVER 2000
Aldo.

View 8 Replies View Related

Tsql

Oct 6, 2007

Hi,

Knows anybody solution for this problem:

http://blog.vyvojar.cz/dotnet/archive/2007/10/05/226475.aspx

Thx a lot

View 5 Replies View Related







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