Join two tables with different field value - sql-server
Would it be possible to join two tables with different field values? I am using MS SQL Server 2008.
Table A (original image, thanks to #EdwardRusu for translating images to text):
+ ----- + --------- + -------- + ----------- + ------------------ + ---------------- + ----------- +
| RecID | Member ID | LoanType | LoanSubType | Application Number | Application Date | Loan Amount |
+ ----- + --------- + -------- + ----------- + ------------------ + ---------------- + ----------- +
| 3 | 00005 | Regular | | 201604002 | 2016-02-28 | 39864.00 |
| 185 | 00005 | Special | Special ... | 201604183 | 2016-10-31 | 10000.00 |
| 318 | 00005 | Regular | | 201605063 | 2016-05-18 | 39864.00 |
| 427 | 00005 | Regular | | 201608021 | 2016-08-18 | 39872.00 |
| 486 | 00005 | Special | Special ... | 201609044 | 2016-09-07 | 10000.00 |
| 589 | 00005 | Regular | | 201611008 | 2016-11-04 | 39872.00 |
| 689 | 00005 | Regular | | 201702004 | 2017-02-02 | 39872.00 |
+ ----- + --------- + -------- + ----------- + ------------------ + ---------------- + ----------- +
Table B (original image):
+ --------------- + --------- + ------ + ----- + ---------- + -------- + -------- + -------- +
| ProjectAcctCode | Member ID | TMonth | TYear | TLastDate | TDebit | TCredit | TBalance |
+ --------------- + --------- + ------ + ----- + ---------- + -------- + -------- + -------- +
| 105350500 | 00005 | 1 | 2017 | 2017-01-31 | 0.00 | 2952.00 | -2952.00 |
| 105350500 | 00005 | 5 | 2016 | 2016-05-31 | 73084.00 | 33220.00 | 39864.00 |
| 105350500 | 00005 | 6 | 2016 | 2016-06-30 | 0.00 | 2951.42 | -2952.42 |
| 105350500 | 00005 | 7 | 2016 | 2016-07-31 | 0.00 | 3014.14 | -3014.14 |
| 105350500 | 00005 | 8 | 2016 | 2016-08-31 | 39872.00 | 33905.26 | 5973.55 |
| 105350500 | 00005 | 9 | 2016 | 2016-09-30 | 0.00 | 2952.00 | -2952.00 |
| 105350500 | 00005 | 10 | 2016 | 2016-10-31 | 0.00 | 3014.73 | -3014.73 |
| 105350500 | 00005 | 11 | 2016 | 2016-11-30 | 39872.00 | 33905.26 | 5966.74 |
| 105351000 | 00005 | 1 | 2017 | 2017-01-31 | 0.00 | 975.03 | -975.03 |
| 105351000 | 00005 | 5 | 2016 | 2016-05-31 | 5000.00 | 1000.00 | 4000.00 |
| 105351000 | 00005 | 6 | 2016 | 2016-06-30 | 0.00 | 1000.00 | -1000.00 |
| 105351000 | 00005 | 7 | 2016 | 2016-07-31 | 0.00 | 1000.00 | -1000.00 |
| 105351000 | 00005 | 8 | 2016 | 2016-08-31 | 0.00 | 1000.00 | -1000.00 |
| 105351000 | 00005 | 9 | 2016 | 2016-09-30 | 10000.00 | 1000.00 | 9000.00 |
| 105351000 | 00005 | 10 | 2016 | 2016-10-31 | 0.00 | 955.82 | -955.82 |
| 105351000 | 00005 | 11 | 2016 | 2016-11-30 | 0.00 | 965.38 | -965.38 |
+ --------------- + --------- + ------ + ----- + ---------- + -------- + -------- + -------- +
I want to get the total TBalance from TableB grouped by MemberID, LoanType, ApplicationNo, ApplicationDate. These two tables should be joined based on LoanType and ProjAcctCode AND ApplicationDate and TLastDate. LoanType and ProjAcctCode have different values. But, "REGULAR" Loantype is equal to "105350500" ProjAcctCode and "SPECIAL LoanType" is equivalent to "105351000" ProjAcctCode.
ApplicationDate should be less than or equal to TLastDate.
So if I will generate records for "REGULAR" loan types , I should have something like this (original image):
+ -------- + -------- + ------------- + --------------- + ---------- + ------------ + --------- + --------- +
| MemberID | LoanType | ApplicationNO | ApplicationDate | LoanAmount | ProjAcctCode | TLastDate | Balance |
+ -------- + -------- + ------------- + --------------- + ---------- + ------------ + --------- + --------- +
| 000005 | Regular | 201608021 | 8/18/2016 | 39,872.00 | 105350500 | 8/31/2016 | 39,871.44 |
+ -------- + -------- + ------------- + --------------- + ---------- + ------------ + --------- + --------- +
But with my query,
SELECT a.MemberID,
(SELECT TOP (1) ApplicationNo
FROM TABLE A
WHERE (MemberID = a.MemberID) AND (ApplicationDate <= b.TLastDate)
ORDER BY ApplicationNo DESC) AS ApplicationNo,
(SELECT TOP (1) LoanAmount
FROM TABLE A AS SAL_APPLICATION_HEADER_1
WHERE (MemberID = a.MemberID) AND (ApplicationDate <= b.TLastDate)
ORDER BY ApplicationNo DESC) AS LoanAmount,
(SELECT TOP (1) ApplicationDate
FROM TABLE A AS SAL_APPLICATION_HEADER_2
WHERE (MemberID = a.MemberID)
AND (ApplicationDate <= b.TLastDate)
ORDER BY ApplicationNo DESC) AS ApplicationDate,
vwSAL_Balance_SL_1.ProjAcctCode,
b.TDebit,
b.TCredit,
b.TBalance AS Balance,
b.TLastDate
FROM TABLE A AS a
INNER JOIN TABLE B AS b ON a.MemberID = b.SLCode
GROUP BY a.MemberID,
b.TDebit,
b.TCredit,
b.TBalance,
b.ProjAcctCode,
b.TLastDate
HAVING (a.MemberID = N'00005') AND (b.TLastDate = '8/31/2016')
I got this result (original image):
+ -------- + ------------- + ---------- + --------------- + ------------ + -------- + -------- + -------- + ---------- +
| MemberID | ApplicationNo | LoanAmount | ApplicationDate | ProjAcctCode | TDebit | TCredit | Balance | TLastDate |
+ -------- + ------------- + ---------- + --------------- + ------------ + -------- + -------- + -------- + ---------- +
| 00005 | 201608021 | 39872.00 | 2016-08-18 | 105351000 | 0.00 | 1000.00 | -1000.00 | 2016-08-31 |
| 00005 | 201608021 | 39872.00 | 2016-08-18 | 105350500 | 39872.00 | 33898.45 | 5973.55 | 2016-08-31 |
+ -------- + ------------- + ---------- + --------------- + ------------ + -------- + -------- + -------- + ---------- +
This might be too long but please help. Thank you.
tl;dr Yes, it is possible. The query block at the end will give you what you want.
Yes, it is possible to join two tables with different field values as long as you know some sort of correlation between the two. I will walk you through the construction of the join statement that gives you what you want. You need three things:
1) Match MemberID and SLCode
2) Match LoanType and ProjAcctCode
3) Match the dates
MemberID and SLCode
Based on your comment above, I'm going to assume that SLCode is the same thing as MemberID in B.
select *
from A
inner join B
on B.MemberID = A.MemberID -- or B.SLCode = A.MemberID
LoanType and ProjAcctCode
In this example, you want to use a case statement in the join, something like
inner join B.ProjAcctCode = case A.LoanType when 'Regular' then 105350500 else 105351000 end
This says that if the LoanType is Regular, then only join records that have ProjAcctCode = 105350500; otherwise join records that have ProjAcctCode 105351000. (Here, LoanType only has two states, so using the else clause to capture Special loans is perfectly fine. If there are more than two states, then you must use additional conditions).
select *
from A
inner join B
on B.MemberID = A.MemberID
and B.ProjAcctCode = case A.LoanType when 'Regular' then 105350500 else 105351000 end
Dates
Getting the date filter right is immediate.
select *
from A
inner join B
on B.MemberID = A.MemberID
and B.ProjAcctCode = case A.LoanType when 'Regular' then 105350500 else 105351000 end
and A.ApplicationDate <= B.TLastDate
Group and Aggregate
Now that you have the tables joined appropriately, you just need to group and aggregate. You can group on anything from A since those fields don't change for the aggregates you want, and you just have to be a little clever in how you select things that came from B. In your question, it looks like you want ProjAcctCode (this doesn't change, so we can group on this too), TLastDate (this does change, so we need to aggregate on some criteria), and TBalance (from which we want the sum). I'm going to assume that you want the latest TLastDate, so your query will be something like
select A.MemberID,
A.LoanType,
A.ApplicationNumber,
A.ApplicationDate,
[anything else you want from A],
B.ProjAcctCode -- aggregate not needed because this doesn't change
max(B.TLastDate) as TLastDate,
sum(B.TBalance) as TBalance
from A
inner join B
on B.MemberID = A.MemberID
and B.ProjAcctCode = case A.LoanType when 'Regular' then 105350500 else 105351000 end
and A.ApplicationDate <= B.TLastDate
group by A.MemberID,
A.LoanType,
A.ApplicationNumber,
A.ApplicationDate,
[anything else you selected from A],
B.ProjAcctCode
This produces the following table
+ -------- + -------- + ----------------- + --------------- + ------------ + ---------- + -------- +
| MemberID | LoanType | ApplicationNumber | ApplicationDate | ProjAcctCode | TLastDate | TBalance |
+ -------- + -------- + ----------------- + --------------- + ------------ + ---------- + -------- +
| 00005 | Regular | 201604002 | 2016-02-08 | 105350500 | 2017-01-31 | 36913.19 |
| 00005 | Special | 201604183 | 2016-10-31 | 105351000 | 2017-01-31 | -2896.23 |
| 00005 | Regular | 201605063 | 2016-05-18 | 105350500 | 2017-01-31 | 36913.19 |
| 00005 | Regular | 201608021 | 2016-08-18 | 105350500 | 2017-01-31 | 3014.75 |
| 00005 | Special | 201609044 | 2016-09-07 | 105351000 | 2017-01-31 | 6103.77 |
| 00005 | Regular | 201611008 | 2016-11-04 | 105350500 | 2017-01-31 | 3014.74 |
+ -------- + -------- + ----------------- + --------------- + ------------ + ---------- + -------- +
Note: The loan with ApplicationNumber 201702004 doesn't appear in the final result because it gets filtered out by date (i.e. its application date is greater than all TLastDate in B).
I just use UNION (per LoanType) in my query to get the desire result.
Related
How to find max(sortnumber) on item code in SQL Server?
I have following SQL Server table ITEM: +------------+-----------+------+--------+-----------+------------+ | Date | item_code | name | in/out | total_qty | SortNumber | +------------+-----------+------+--------+-----------+------------+ | 08/07/2019 | 001 | A | -50 | 100 | 8 | | 07/07/2019 | 001 | A | 50 | 100 | 7 | | 06/07/2019 | 003 | C | 25 | 25 | 6 | | 05/07/2019 | 001 | A | 50 | 50 | 5 | | 04/07/2019 | 002 | B | 100 | 200 | 4 | | 03/07/2019 | 003 | C | -25 | 0 | 3 | | 02/07/2019 | 003 | C | 25 | 25 | 2 | | 01/07/2019 | 002 | B | 100 | 100 | 1 | +------------+-----------+------+--------+-----------+------------+ I've tried: select itemcode, max(Sort_Number) from ITEM group by item_code order by item_code asc but I want result: +---------------------+-----------+------------------+ | Distinct(item_code) | Total_qty | Max(Sort_Number) | +---------------------+-----------+------------------+ | 001 | 100 | 8 | | 002 | 200 | 4 | | 003 | 25 | 6 | +---------------------+-----------+------------------+ Can anyone help me?
The below query gives you the desired result - With cteItem as ( select item_code, total_qty, SortNumber, Row_Number() over (partition by item_code order by SortNumber desc) maxSortNumber from ITEM ) select item_code, total_qty, SortNumber from cteItem where maxSortNumber = 1
just need to add max(sort_number) to your query select item_code ,max(total_qty), max(sort_number) from ITEM group by item_code order by item_code asc
Can recursion start from a specific record in a table?
I'm trying to calculate depreciation on vehicles. If there is a rebate on a vehicle, I need to stop the depreciation, factor in the rebaste based on the month it look affect, and resume the depreciation calculation. A vehicle depreciates at a flat rate of 2% every month with 50 months being the point of 100% depreciation. When a rebate appears, I can stop the depreciation, but I don't know how to make it start again from a certain month. Below is an example of the table's deprecation up to directly before the rebate: +----------+-------+------------+--------------+------------+------------+ | Vehicle# | month | depDate | Initial Cost | Monthlydep | totaldep | +----------+-------+------------+--------------+------------+------------+ | 12451 | 1 | 2015-08-01 | 44953.24 | 899.06 | 899.0648 | | 12451 | 2 | 2015-09-01 | 44953.24 | 899.06 | 1798.1296 | | ------- | ----- | ----- | ----- | ----- | ----- | | 12451 | 42 | 2019-01-01 | 44953.24 | 899.06 | 37760.7216 | | 12451 | 43 | 2019-02-01 | 44953.24 | 899.06 | 38659.7864 | +----------+-------+------------+--------------+------------+------------+ Then let's say that a rebate comes in this month (2019-03-01) it needs to be factored in and then the depreciation needs to be recalculated from that month onwards the. How do I restart the depreciation from month 43 instead of it going through everything? For example let's say that we get a rebate in month 44 for $200 dollars. The table should look like something below: +----------+-------+------------+--------------+------------+------------+ | Vehicle# | month | depDate | Initial Cost | Monthlydep | totaldep | +----------+-------+------------+--------------+------------+------------+ | 12451 | 43 | 2019-02-01 | 44953.24 | 899.06 | 38659.7864 | | 12451 | 44 | 2019-03-01 | 44953.24 | 1099.06 | 39758.8464 | | 12451 | 45 | 2019-04-01 | 44953.24 | 1099.06 | 40857.9064 | | 12451 | 46 | 2019-05-01 | 44953.24 | 1099.06 | 41956.9664 | | 12451 | 47 | 2019-06-01 | 44953.24 | 1099.06 | 43056.0264 | | 12451 | 48 | 2019-06-01 | 44953.24 | 1099.06 | 44155.0864 | | 12451 | 49 | 2019-06-01 | 44953.24 | 1099.06 | 45254.1464 | +----------+-------+------------+--------------+------------+------------+ So month 49 would be the final month because the totalDep is equal to or higher than the initial cost My sample code is below. If you remove the first cte and the join inner join in the top part of the union then that is the working depreciation calculation: ;With cte As( Select bd.[VehicleID] ,Max(bd.[Month]) As month ,Max(DateAdd(DAY,1,EOMONTH(DepreciationReportDate,-1))) As DepreciationReportDate ,Max(bd.MonthlyDepreciation) As MonthlyDepreciation ,Max(bd.AdjustedPurchaseCost) As AdjustedPurchaseCost ,Max(AccumulatedDepreciation) As AccumulatedDepreciation From Work.dbo.DepreciationSchedule bd Group By bd.VehicleID ) ,cte_CreateRows As ( Select bd.[VehicleID] ,bd.[Month] ,DATEADD(DAY,1,EOMONTH(bd.DepreciationReportDate,-1)) As DepreciationReportDate ,bd.MonthlyDepreciation ,bd.AdjustedPurchaseCost ,bd.AccumulatedDepreciation From Work.dbo.DepreciationSchedule bd Inner Join cte cte On cte.VehicleID = bd.VehicleID And cte.month = bd.Month Union All Select bd.[VehicleID] ,[Month] = Cast(cr.[Month]+1 As int) ,DATEADD(DAY,1,EOMONTH(DateAdd(Month, 1, cr.DepreciationReportDate),-1)) As DepreciationReportDate ,bd.MonthlyDepreciation ,bd.AdjustedPurchaseCost ,AccumulatedDepreciation = cr.AccumulatedDepreciation + cr.MonthlyDepreciation From Work.dbo.DepreciationSchedule bd Inner Join cte_CreateRows cr On bd.[VehicleID] = cr.[VehicleID] Where cr.AccumulatedDepreciation < cr.AdjustedPurchaseCost And DateAdd(Month,1, DateAdd(DAY,1,EOMONTH(cr.DepreciationReportDate,-1))) < DATEADD(DAY,1,EOMONTH(GetDate(),-1)) ) Select a.VehicleID ,a.Month ,a.DepreciationReportDate ,Cast(a.MonthlyDepreciation As Decimal(12,2)) As 'Monthly Depreciation Expense' ,a.AdjustedPurchaseCost ,a.AccumulatedDepreciation From [cte_CreateRows] As a Order By a.VehicleID, a.Month
SQL Server add all rows where a condition is validate
I have a SQL Server database in which I need to add all the cost for a job family. I have a table like this Table : work +-------+-----------+-----------+---------+ | wonum | cost1 | cost2 | wogroup | +-------+-----------+-----------+---------+ | 1 | 30.12 | 157.14 | 1 | | 2 | 110.10 | 0.00 | 1 | | 3 | 12.67 | 45.45 | 1 | | 4 | 0.00 | 0.00 | 4 | | 5 | 400.00 | 11.54 | 4 | +-------+-----------+-----------+---------+ I need to add cost1 and cost2 for all the row who have the same wogroup but only for the on where wonum = wogroup. Like this +-------+-----------+-----------+---------+---------+ | wonum | cost1 | cost2 | wogroup | total | +-------+-----------+-----------+---------+---------+ | 1 | 30.12 | 157.14 | 1 | 355.48 | | 2 | 110.10 | 0.00 | 1 | null | | 3 | 12.67 | 45.45 | 1 | null | | 4 | 0.00 | 0.00 | 4 | 411.54 | | 5 | 400.00 | 11.54 | 4 | null | +-------+-----------+-----------+---------+---------+ In a perfect world, the null value would be the sum of cost1 and cost2 for the row but I'm not sure if it is possible... EDIT: I can only do a select, it is for a BiRT report
Since this can change with more wonum being added, I'd have this as a VIEW declare #work table (wonum int , cost1 decimal (6,3), cost2 decimal (6,3) , wogroup int) insert into #work values (1,30.12,157.14,1), (2,110.10,0.00,1), (3,12.67,45.45,1), (4,0.00,0.00,4), (5,400.00,11.54,4) select *, total = case when wonum = min(wonum) over (partition by wogroup) then sum(cost1) over (partition by wogroup) + sum(cost2) over (partition by wogroup) end from #work RETURNS +-------+-----------+-----------+---------+---------+ | wonum | cost1 | cost2 | wogroup | total | +-------+-----------+-----------+---------+---------+ | 1 | 30.12 | 157.14 | 1 | 355.48 | | 2 | 110.10 | 0.00 | 1 | null | | 3 | 12.67 | 45.45 | 1 | null | | 4 | 0.00 | 0.00 | 4 | 411.54 | | 5 | 400.00 | 11.54 | 4 | null | +-------+-----------+-----------+---------+---------+ YOUR QUERY select *, total = case when wonum = min(wonum) over (partition by wogroup) then sum(cost1) over (partition by wogroup) + sum(cost2) over (partition by wogroup) else null end from work
Populating Rows Based On Ranges
I am working on a query for the accounting department. I have a report template that provides me with Headers, Detail, Total, and other row types. Where the row type is "D," I have a range of accounts (Start_Account/End_Account). I'm trying to write a query that will bump up against general ledger data. I'd like to be able to populate each row with the appropriate heading description. Admittedly, I am stumped, short of doing it manually. +-----------+--------------+----------+---------------+-------------+-----------+-------------------+---------------------------+ | Report_ID | Row_Sequence | Row_Type | Start_Account | End_Account | Level_Num | Reverse_Sign_Flag | Heading_Description | +-----------+--------------+----------+---------------+-------------+-----------+-------------------+---------------------------+ | 06 | 001 | H | | | 1 | | CONSTRUCTION INCOME | | 06 | 002 | D | 3000 | 3099 | 10 | Y | | | 06 | 003 | D | 3801 | 3801 | 10 | Y | | | 06 | 004 | T | 3000 | 3099 | 11 | Y | TOTAL INCOME | | 06 | 005 | I | 3801 | 3801 | 0 | | | | 06 | 011 | H | | | 1 | | DIRECT CONSTRUCTION COSTS | | 06 | 012 | D | 4000 | 4001 | 10 | | | | 06 | 013 | D | 4011 | 4031 | 10 | | | | 06 | 014 | D | 4041 | 4041 | 10 | | | | 06 | 015 | T | 4000 | 4099 | 11 | | TOTAL DIRECT EXPENSES | | 06 | 016 | E | 4002 | 4002 | 0 | | | | 06 | 017 | E | 4032 | 4032 | 0 | | | | 06 | 018 | E | 4051 | 4051 | 0 | | | | 06 | 019 | T | 3000 | 3099 | 12 | Y | GROSS PROFIT FROM JOBS | | 06 | 020 | I | 3801 | 3801 | 0 | | | | 06 | 021 | I | 4000 | 4099 | 0 | | | | 06 | 022 | H | | | 1 | | OVERHEAD APPLIED TO JOBS | | 06 | 023 | D | 3402 | 3402 | 10 | Y | | | 06 | 024 | D | 3404 | 3404 | 10 | Y | | | 06 | 025 | D | 3417 | 3417 | 10 | Y | | | 06 | 026 | D | 5432 | 5432 | 10 | Y | | | 06 | 027 | D | 5471 | 5471 | 10 | Y | | | 06 | 028 | D | 5494 | 5494 | 10 | Y | | | 06 | 029 | D | 5495 | 5495 | 10 | Y | | | 06 | 035 | T | 3402 | 3402 | 12 | Y | ADJUST BURDEN TO ACTUAL | +-----------+--------------+----------+---------------+-------------+-----------+-------------------+---------------------------+ As outputs, I would have: Start_Account End_Account Heading_1 Heading_2 Heading_3 Using the JPG: Level_Num 1 would correspond to Heading_1 Level_Num 11 would correspond to Heading_2 Levl_Num 12 would be Heading_3 So, for example, for Start_Account = 3000, End_Account = 3099: Heading_1 would be "Construction Income," Heading_2 would be "Total Income," Heading_3 would be "Gross Profit From Jobs." Now when I join to the general ledger detail, I'd like to be able to look up the proper header titles based on the start and end accounts.
It is really hard to understand what you are trying to achieve. Anyway here is a script that dynamically creates headings. You will propbably have to adjust the logic to fit your requirements, but it should be a good starting point: declare #startAccount int = 3000 declare #endAccount int = 3099 declare #tmp table(Report_ID varchar(10), Row_Sequence varchar(10), Row_Type varchar(1), Start_Account int, End_Account int, Level_Num int, Reverse_Sign_Flag varchar(1), Heading_Description varchar(max)) insert into #tmp values ('06','001','H',null,null,1 ,'','CONSTRUCTION INCOME') ,('06','002','D',3000,3099,10,'Y','') ,('06','003','D',3801,3801,10,'Y','') ,('06','004','T',3000,3099,11,'Y','TOTAL INCOME') ,('06','005','I',3801,3801,0 ,'','') ,('06','011','H',null,null,1 ,'','DIRECT CONSTRUCTION COSTS') ,('06','012','D',4000,4001,10 ,'','') ,('06','013','D',4011,4031,10 ,'','') ,('06','014','D',4041,4041,10 ,'','') ,('06','015','T',4000,4099,11 ,'','TOTAL DIRECT EXPENSES') ,('06','016','E',4002,4002,0 ,'','') ,('06','017','E',4032,4032,0 ,'','') ,('06','018','E',4051,4051,0 ,'','') ,('06','019','T',3000,3099,12,'Y','GROSS PROFIT FROM JOBS') ,('06','020','I',3801,3801,0 ,'','') ,('06','021','I',4000,4099,0 ,'','') ,('06','022','H',NULL,NULL,1 ,'','OVERHEAD APPLIED TO JOBS') ,('06','023','D',3402,3402,10 ,'Y','') ,('06','024','D',3404,3404,10 ,'Y','') ,('06','025','D',3417,3417,10 ,'Y','') ,('06','026','D',5432,5432,10 ,'Y','') ,('06','027','D',5471,5471,10 ,'Y','') ,('06','028','D',5494,5494,10 ,'Y','') ,('06','029','D',5495,5495,10 ,'Y','') ,('06','035','T',3402,3402,12 ,'Y','ADJUST BURDEN TO ACTUAL') DECLARE #Heading_1 varchar(100) , #Heading_2 varchar(100) , #Heading_3 varchar(100) , #minRowSequence varchar(10) select #minRowSequence = min(Row_Sequence) from #tmp where Start_Account=#startAccount and End_Account=#endAccount select #Heading_1 = Heading_Description from #tmp where isnull(Start_Account,'')='' and isnull(End_Account,'')='' and Level_Num=1 and Row_Sequence < #minRowSequence select #Heading_2 = Heading_Description from #tmp where Start_Account=#startAccount and End_Account=#endAccount and Level_Num=11 select #Heading_3 = Heading_Description from #tmp where Start_Account=#startAccount and End_Account=#endAccount and Level_Num=12 DECLARE #sql nvarchar(max) = '' set #sql = #sql + 'select ' + cast(#startAccount as varchar(max)) + ' AS Start_Account, ' set #sql = #sql + cast(#endAccount as varchar(max)) +' AS End_Account, ' set #sql = #sql + '''' + #Heading_1 + ''' AS Heading_1, ' set #sql = #sql + '''' + #Heading_2 + ''' AS Heading_2, ' set #sql = #sql + '''' + #Heading_3 + ''' AS Heading_3 ' exec(#sql) Output:
Select a specific line if i have the same information
I have a table with a data as bellow : +--------+----------+-------+------------+--------------+ | month | code | type | date | PersonID | +--------+----------+-------+------------+--------------+ | 201501 | 178954 | 3 | 2014-12-3 | 10 | | 201501 | 178954 | 3 | 2014-12-3 | 10 | | 201501 | 178955 | 2 | 2014-12-13 | 10 | | 201501 | 178955 | 2 | 2014-12-13 | 10 | | 201501 | 178956 | 2 | 2014-12-11 | 10 | | 201501 | 178958 | 1 | 2014-12-10 | 10 | | 201501 | 178959 | 2 | 2014-12-12 | 15 | | 201501 | 178959 | 2 | 2014-12-12 | 15 | | 201501 | 178954 | 1 | 2014-12-11 | 13 | | 201501 | 178954 | 1 | 2014-12-11 | 13 | +--------+----------+-------+------------+--------------+ In my first 6 lines i have the same PersonID in the same Month What i want if i have the same personID in the same Month i want to select the person who have the type is 2 with the recent date in my case the output will be like as bellow: +--------+--------+------+------------+----------+ | month | code | type| date | PersonID | +--------+--------+------+------------+----------+ | 201501 | 178955 | 2 | 2014-12-13 | 10 | | 201501 | 178959 | 2 | 2014-12-12 | 15 | | 201501 | 178954 | 2 | 2014-12-11 | 13 | +--------+--------+------+------------+----------+ Also if they are some duplicate rows i don't want to display it They are any solution to that ?
Simply use GROUP BY: https://msdn.microsoft.com/de-de/library/ms177673(v=sql.120).aspx SELECT mont, code, ... FROM tabelname GROUP BY PersonID, date, ... Note that you have to specifiy all columns in the group by.
SELECT DISTINCT A.month, A.code, A.type, B.date, B.PersonID FROM YourTable A INNER JOIN (SELECT PersonID, MAX(date) as date FROM YourTable GROUP BY PersonID) B ON (A.PersonID = B.PersonID AND A.date = B.date) WHERE A.type = 2 ORDER BY B.date DESC, A.PersonID Just in case you/others are still wondering.