How do i write a query for Profit and loss statement by division in SAP Business One - sapb1

Please help me with this , This is the query needed by the client where they get profit and loss statement from the crystal by division. So i need to write a query or procedure to retrieve it

Hope the below helps. I used it before
USE [EUROPA_PROD_DB]
GO
/****** Object: View [dbo].[vw_Transactions] Script Date: 05/04/2012 12:51:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[vw_Transactions] AS
SELECT
TA.AcctCode,TA.AcctName,TA.GroupMask,TA.Levels,TA.ActType,TA.L1Parent,TA.L2Parent,
TA.L3Parent,TA.L4Parent,
TH.TransId,TH.TransType,TH.RefDate PostingDate,TH.DueDate,
TH.TaxDate,TD.Account,TD.Debit,TD.Credit
FROM OJDT TH
INNER JOIN JDT1 TD ON TH.TransId=TD.TransId
INNER JOIN vw_AccountDetails TA ON TD.Account=TA.AcctCode
GO
USE [EUROPA_PROD_DB]
GO
/****** Object: View [dbo].[vw_AccountDetails] Script Date: 05/04/2012 12:50:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[vw_AccountDetails]
AS
SELECT TA.AcctCode,TA.AcctName,TA.GroupMask,TA.Levels,TA.ActType,
CASE Levels
WHEN 1 THEN
TA.AcctName
WHEN 2 THEN
(SELECT TA1.AcctName FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)
WHEN 3 THEN
(SELECT TA3.AcctName FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA2.FatherNum FROM OACT TA2 WHERE TA2.AcctCode=
(SELECT TA1.AcctCode FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)))
WHEN 4 THEN
(SELECT TA3.AcctName FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA3.FatherNum FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA2.FatherNum FROM OACT TA2 WHERE TA2.AcctCode=
(SELECT TA1.AcctCode FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum))))
WHEN 5 THEN
(SELECT TA3.AcctName FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA3.FatherNum FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA3.FatherNum FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA2.FatherNum FROM OACT TA2 WHERE TA2.AcctCode=
(SELECT TA1.AcctCode FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)))))
ELSE '' END AS L1Parent,
CASE Levels
WHEN 1 THEN
''
WHEN 2 THEN
TA.AcctName
WHEN 3 THEN
(SELECT TA1.AcctName FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)
WHEN 4 THEN
(SELECT TA3.AcctName FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA2.FatherNum FROM OACT TA2 WHERE TA2.AcctCode=
(SELECT TA1.AcctCode FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)))
WHEN 5 THEN
(SELECT TA3.AcctName FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA3.FatherNum FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA2.FatherNum FROM OACT TA2 WHERE TA2.AcctCode=
(SELECT TA1.AcctCode FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum))))
ELSE '' END AS L2Parent,
CASE Levels
WHEN 1 THEN
''
WHEN 2 THEN
''
WHEN 3 THEN
TA.AcctName
WHEN 4 THEN
(SELECT TA1.AcctName FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)
WHEN 5 THEN
(SELECT TA3.AcctName FROM OACT TA3 WHERE TA3.AcctCode=
(SELECT TA2.FatherNum FROM OACT TA2 WHERE TA2.AcctCode=
(SELECT TA1.AcctCode FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)))
ELSE '' END AS L3Parent,
CASE Levels
WHEN 1 THEN
''
WHEN 2 THEN
''
WHEN 3 THEN
''
WHEN 4 THEN
TA.AcctName
WHEN 5 THEN
(SELECT TA1.AcctName FROM OACT TA1 WHERE TA1.AcctCode=TA.FatherNum)
ELSE '' END AS L4Parent
FROM OACT TA
WHERE TA.Postable='Y'
GO
CREATE PROCEDURE sp_CustomProfit_And_Loss
(
#BeginDate DATETIME,
#EndDate DATETIME
)
AS
BEGIN
SELECT L1Parent,L2Parent,Balance,RowOrder
FROM fn_CustomProfit_And_Loss(#BeginDate,#EndDate)
order by RowOrder
END
CREATE FUNCTION fn_CustomProfit_And_Loss
(
#BeginDate DATETIME,
#EndDate DATETIME
)
RETURNS #table TABLE(
L1Parent VARCHAR(72),
L2Parent VARCHAR(72),
Balance MONEY,
RowOrder INT
)
AS
BEGIN
SET #BeginDate=CAST(YEAR(#BeginDate) AS CHAR(4))+'-'+CAST(MONTH(#BeginDate) AS CHAR(2)) +'-'+ CAST(DAY(#BeginDate) AS CHAR(2))
SET #EndDate=CAST(YEAR(#EndDate) AS CHAR(4))+'-'+CAST(MONTH(#EndDate) AS CHAR(2)) +'-'+ CAST(DAY(#EndDate) AS CHAR(2))
--SET #EndDate='2012-12-31'
INSERT INTO #table
SELECT
CASE L1Parent WHEN 'Turnover' THEN 'Income' ELSE L1Parent END L1Parent,
L2Parent,
SUM(Credit-Debit) Balance,
1 RowOrder
FROM vw_Transactions
WHERE GroupMask=4--Income
AND PostingDate BETWEEN #BeginDate AND #EndDate
GROUP BY L1Parent,L2Parent
UNION ALL
SELECT
CASE L1Parent WHEN 'Cost of Sales' THEN 'Cost Of Goods Sold' ELSE L1Parent END L1Parent,
L2Parent,
SUM(Debit-Credit) Balance,
2 RowOrder
FROM vw_Transactions
WHERE GroupMask=5--COGS
AND PostingDate BETWEEN #BeginDate AND #EndDate
GROUP BY L1Parent,L2Parent
UNION ALL
SELECT
CASE L1Parent WHEN 'Operating Costs' THEN 'Expenses' ELSE L1Parent END L1Parent,
L2Parent,
SUM(Debit-Credit) Balance,
3 RowOrder
FROM vw_Transactions
WHERE GroupMask IN(6,71,81)--Expenses
AND PostingDate BETWEEN #BeginDate AND #EndDate
GROUP BY L1Parent,L2Parent
RETURN
END

Related

Get a column value that showed up more than 3 times in a table

I am trying to filter out and show all the item_number that showed up at least 3 times or more. Below is my SQL query that I am have written.
SELECT row_number() over(partition by i.item_number order by i.item_number) row_num
,i.item_number
,sto.location_id
,sto.actual_qty
,trn.source_location_id
,trn.tran_qty
FROM #items i
LEFT JOIN (select loc.location_wh, sto.item_number, sto.location_id, sto.actual_qty, sto.status from t_stored_item sto WITH (NOLOCK)
INNER JOIN t_location loc WITH (NOLOCK)
on loc.location_id = sto.location_id
where loc.location_wh = '80'
and loc.type = 'I') sto
ON sto.item_number = i.item_number
LEFT JOIN (select t.item_number, t.source_location_id, sum(t.tran_qty) tran_qty from t_tran_log t WITH (NOLOCK)
WHERE t.tran_type = '305'
and convert(date, end_tran_date AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time') = '2021-11-16'
GROUP BY t.item_number, t.source_location_id) trn
on trn.item_number = i.item_number
and trn.source_location_id = sto.location_id
WHERE sto.location_id IS NOT NULL
The data looks like this
row_num item_number location_id actual_qty source_location_id tran_qty
1 1040370 AL-27-03-A 120 NULL NULL
2 1040370 BH-16-04-A 96 NULL NULL
1 1089630 BV-59-04-F 192 NULL NULL
2 1089630 BW-35-05-D 96 NULL NULL
3 1089630 BQ-28-04-A 576 NULL NULL
1 1132345 BZ-32-07-C 804 NULL NULL
2 1132345 AG-51-02-B 588 NULL NULL
3 1132345 BX-28-08-C 60 NULL NULL
4 1132345 AH-18-06-B 600 NULL NULL
5 1132345 BX-14-04-C 108 NULL NULL
Now I want to show all the item_numbers that showed up 3 times at least or more. As you can see, 1089630 showed up 3 times so these should show up in my next nesting query. I tried this but it showed up empty.
;with temp as (
SELECT row_number() over(partition by i.item_number order by i.item_number) row_num
,i.item_number
,sto.location_id
,sto.actual_qty
,trn.source_location_id
,trn.tran_qty
FROM #items i
LEFT JOIN (select loc.location_wh, sto.item_number, sto.location_id, sto.actual_qty, sto.status from t_stored_item sto WITH (NOLOCK)
INNER JOIN t_location loc WITH (NOLOCK)
on loc.location_id = sto.location_id
where loc.location_wh = '80'
and loc.type = 'I') sto
ON sto.item_number = i.item_number
LEFT JOIN (select t.item_number, t.source_location_id, sum(t.tran_qty) tran_qty from t_tran_log t WITH (NOLOCK)
WHERE t.tran_type = '305'
and convert(date, end_tran_date AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time') = '2021-11-16'
GROUP BY t.item_number, t.source_location_id) trn
on trn.item_number = i.item_number
and trn.source_location_id = sto.location_id
WHERE sto.location_id IS NOT NULL
--ORDER BY item_number
)
select row_num, item_number, location_id, actual_qty, source_location_id, tran_qty
from temp
GROUP BY row_num, item_number, location_id, actual_qty, source_location_id, tran_qty
having count(item_number) >= 3
Can anyone please help?

Show multiple row results in SQL Server 2005 as a single row

I need a query in SQL Server 2005 to combine results from multiple rows into a single row
The data I have relates to clothing sizes like this:
# Item No. Garment SKU In Stock
1 CUR211NA-L CUR211NA 0.00
2 CUR211NA-LB CUR211NA 10.00
3 CUR211NA-M CUR211NA 0.00
4 CUR211NA-MB CUR211NA 3.00
5 CUR211NA-S CUR211NA 0.00
6 CUR211NA-SB CUR211NA -9.00
7 CUR211NA-XL CUR211NA 0.00
8 CUR211NA-XXL CUR211NA 0.00
9 CUR211NA-YTH CUR211NA 7.00
I need to show a single SKU code row with the sizes in columns like this:
SB MB LB YTH S M L XL XXL
CUR211NA -9 3 10 7 0 0 0 0 0
What I have so far which is showing the quantities correctly but placing every item on a seperate row
SELECT distinct T0.[U_GarmentSKU], T0.[U_Garment_Title],
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('47900') and t0.itemcode=t1.itemcode) 'SB',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('39600') and t0.itemcode=t1.itemcode) as 'MB',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('38500') and t0.itemcode=t1.itemcode) as 'LB',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('50100') and t0.itemcode=t1.itemcode) as 'YTH',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('47700') and t0.itemcode=t1.itemcode) as 'S',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('39400') and t0.itemcode=t1.itemcode) as 'M',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('38300') and t0.itemcode=t1.itemcode) as 'L',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('49200','48700') and t0.itemcode=t1.itemcode) as 'XL',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('49700','49300') and t0.itemcode=t1.itemcode) as 'XXL',
(select T0.[OnHand] from oitm t1 where T0.[U_GarmentSize] IN ('49800') and t0.itemcode=t1.itemcode) as 'XXXL'
FROM OITM T0 WHERE T0.[U_GarmentSKU] like 'SUR%' and T0.[U_StkStat] = 'G'
Don't use a subquery. Either use pivot (well, not in SQL Server 2005) or conditional aggregation:
SELECT T0.[U_GarmentSKU], T0.[U_Garment_Title],
SUM(CASE WHEN T0.[U_GarmentSize] IN ('47900') THEN T0.[OnHand] ELSE 0
END) as SB,
. . .
FROM OITM T0
WHERE T0.[U_GarmentSKU] like 'SUR%' and T0.[U_StkStat] = 'G'
GROUP BY T0.[U_GarmentSKU], T0.[U_Garment_Title];
The same conditional aggregation as Gordon Linoff's answer, just expanded out for all of the columns in the question:
select
t.[U_GarmentSKU]
, t.[U_Garment_Title]
, [SB] = sum(case when t.[U_GarmentSize] in ('47900') then t.[OnHand] else 0 end)
, [MB] = sum(case when t.[U_GarmentSize] in ('39600') then t.[OnHand] else 0 end)
, [LB] = sum(case when t.[U_GarmentSize] in ('38500') then t.[OnHand] else 0 end)
, [YTH] = sum(case when t.[U_GarmentSize] in ('50100') then t.[OnHand] else 0 end)
, [S] = sum(case when t.[U_GarmentSize] in ('47700') then t.[OnHand] else 0 end)
, [M] = sum(case when t.[U_GarmentSize] in ('39400') then t.[OnHand] else 0 end)
, [L] = sum(case when t.[U_GarmentSize] in ('38300') then t.[OnHand] else 0 end)
, [XL] = sum(case when t.[U_GarmentSize] in ('49200','48700') then t.[OnHand] else 0 end)
, [XXL] = sum(case when t.[U_GarmentSize] in ('49700','49300') then t.[OnHand] else 0 end)
, [XXXL] = sum(case when t.[U_GarmentSize] in ('49800') then t.[OnHand] else 0 end)
from oitm t
where t.[U_GarmentSKU] like 'SUR%'
and t.[U_StkStat] = 'G'
group by t.[U_GarmentSKU], t.[U_Garment_Title]

Cognos Report Studio 10.2.2 case statement sql logic

I am trying to get this sql logic to work and the last part is where i do not have my logic correct.
I need to bring back readmits for providers that have listed as ID_1 & ID_2. If a person has a readmit within 30 days then they get a readmit_conf_30 number even if they went to another place. I need to have the original provider numbers and the other providers in the report if they have a readmit within 30 days of of each other.
I have tried many ways and am at a loss for how to word it. Group1 is for providers that i am looking for. Group2 is for other providers. Group3 unions them together and Group4 i try to assign them Y/N whether i want them on report. That is where i need help in the case logic.
Thanks for the help.
Code:
WITH Group1 AS
(
SELECT
A.MEMBER, B.SEX, B.DOB, B.LAST_NAME, B.FIRST_NAME,
A.PROVIDER_ID, C.PROVIDER_NAME, A.CONF_NUM, A.BEG_DT, A.END_DT, A.TOS_I_4, A.DIS_STAT, A.AMT_EQV, A.AMT_PAY, A.AMT_REQ
, A.READMIT_INDEX_30, A.READMIT_30, A.READMIT_CONF_30, '04/30/2014' as DateCheck
, '341425870018' AS ID_1
, '341425870052' AS ID_2
FROM CONFINEMENTS A
LEFT JOIN MEMINFO B ON A.MEMBER = B.MEMBER
LEFT JOIN PROVINFO C ON A.PROVIDER_ID = C.PROVIDER_ID
LEFT JOIN MAP_DATE_RANGE D ON D.IA_TIME = A.IA_TIME
WHERE
A.CUST_OPL_MED IN ('A$*', 'B$*', 'N$*', 'P$*', 'D$*', ' 'Unspecified$UNK')
AND A.BEG_DT >= '05/01/2013' and A.beg_dt <'05/01/2014'
and A.PROVIDER_ID Like '341425870%'
and (A.READMIT_30 = 1 OR A.READMIT_30 = 0)
--AND A.DIS_STAT <> 20
),
GROUP2 AS (
SELECT
A.MEMBER, B.SEX, B.DOB, B.LAST_NAME, B.FIRST_NAME, A.PROVIDER_ID, C.PROVIDER_NAME
, A.CONF_NUM, A.BEG_DT, A.END_DT, A.TOS_I_4, A.DIS_STAT, A.AMT_EQV, A.AMT_PAY, A.AMT_REQ
, A.READMIT_INDEX_30, A.READMIT_30, A.READMIT_CONF_30, '04/30/2014' as DateCheck
, '341425870018' AS ID_1
, '341425870052' AS ID_2
FROM CONFINEMENTS A
LEFT JOIN MEMINFO B ON A.MEMBER = B.MEMBER
LEFT JOIN PROVINFO C ON A.PROVIDER_ID = C.PROVIDER_ID
LEFT JOIN MAP_DATE_RANGE D ON D.IA_TIME = A.IA_TIME
WHERE
A.CUST_OPL_MED IN ('A$*', 'B$*', 'N$*', 'P$*', 'D$*', 'Unspecified$UNK')
AND A.BEG_DT >= '05/01/2013' and A.beg_dt <'05/01/2014'
--and A.PROVIDER_ID Like '341425870%'
and (A.READMIT_30 = 1 OR A.READMIT_30 = 0)
--AND A.DIS_STAT <> 20
),
GROUP3 AS (
Select *, DATEADD(dd, 30, datecheck) AS MaxdateAllowed from Group1
union
select *, DATEADD(dd, 30, datecheck) AS MaxdateAllowed from GROUP2
),
Group4 AS (
select *
, case when PROVIDER_ID <> ID_1 and readmit_conf_30 is not null THEN 'Y'
when PROVIDER_ID <> ID_2 and readmit_conf_30 is not null THEN 'Y'
when PROVIDER_ID = ID_1 and readmit_conf_30 is not null THEN 'Y'
when PROVIDER_ID = ID_2 and readmit_conf_30 is not null THEN 'Y'
when PROVIDER_ID = ID_1 THEN 'Y'
when PROVIDER_ID = ID_2 THEN 'Y'
when PROVIDER_ID <> ID_1 THEN 'N'
when PROVIDER_ID <> ID_2 THEN 'N'
ELSE 'B'
END AS GoodRecord
FROM Group3
where maxdateallowed > beg_dt and READMIT_INDEX_30 = 1
--and (READMIT_30 = 1 OR READMIT_30 = 0)
)
SELECT * FROM Group4
WHERE GoodRecord = 'Y'
order by conf_num
I figured it out.
SQL Code Below :-
WITH Group1 AS (
SELECT A.MEMBER, B.SEX, B.DOB, B.LAST_NAME, B.FIRST_NAME, A.PROVIDER_ID, C.PROVIDER_NAME
, A.CONF_NUM, A.BEG_DT, A.END_DT, A.TOS_I_4, A.DIS_STAT, A.AMT_EQV, A.AMT_PAY, A.AMT_REQ
, A.READMIT_INDEX_30, A.READMIT_30, A.READMIT_CONF_30
FROM CONFINEMENTS A
LEFT JOIN MEMINFO B ON A.MEMBER = B.MEMBER
LEFT JOIN PROVINFO C ON A.PROVIDER_ID = C.PROVIDER_ID
LEFT JOIN MAP_DATE_RANGE D ON D.IA_TIME = A.IA_TIME
WHERE A.CUST_OPL_MED IN ('A$*', 'B$*', 'N$*', 'P$*', 'D$*', 'Unspecified$UNK')
AND A.BEG_DT >= '05/01/2013' and A.beg_dt <'05/01/2014'
and A.PROVIDER_ID Like '341425870%'
and (A.READMIT_30 = 1 OR A.READMIT_30 = 0)
),
GROUP2 AS (
SELECT AA.MEMBER, AA.READMIT_CONF_30
FROM Group1 AA
WHERE AA.READMIT_CONF_30 > 0
),
Group3 AS (
Select AA.MEMBER, A.READMIT_CONF_30, A.CONF_NUM
,B.SEX, B.DOB, B.LAST_NAME, B.FIRST_NAME, A.PROVIDER_ID, C.PROVIDER_NAME
, A.BEG_DT, A.END_DT, A.TOS_I_4, A.DIS_STAT, A.AMT_EQV, A.AMT_PAY, A.AMT_REQ
, A.READMIT_30, A.READMIT_INDEX_30
FROM GROUP2 AA
LEFT JOIN CONFINEMENTS A ON A.MEMBER = AA.MEMBER AND AA.READMIT_CONF_30 = A.CONF_NUM
LEFT JOIN MEMINFO B ON A.MEMBER = B.MEMBER
LEFT JOIN PROVINFO C ON A.PROVIDER_ID = C.PROVIDER_ID
LEFT JOIN MAP_DATE_RANGE D ON D.IA_TIME = A.IA_TIME
WHERE A.CUST_OPL_MED IN ('A$*', 'B$*', 'N$*', 'P$*', 'D$*', 'Unspecified$UNK')
and (A.READMIT_30 = 1 OR A.READMIT_30 = 0)
)
select
MEMBER, READMIT_CONF_30
,SEX, DOB, LAST_NAME, FIRST_NAME, PROVIDER_ID, PROVIDER_NAME
, CONF_NUM, BEG_DT, END_DT, TOS_I_4, DIS_STAT, AMT_EQV, AMT_PAY, AMT_REQ
, READMIT_30, READMIT_INDEX_30
from group1
union
select
MEMBER, READMIT_CONF_30
,SEX, DOB, LAST_NAME, FIRST_NAME, PROVIDER_ID, PROVIDER_NAME
, CONF_NUM, BEG_DT, END_DT, TOS_I_4, DIS_STAT, AMT_EQV, AMT_PAY, AMT_REQ
, READMIT_30, READMIT_INDEX_30
from Group3
order by conf_num

MSSQL - 2 Tables with multiple rows merge in one table

I have 2 selects which returns 2 tables, in each table I have 12 rows, and 2 column, now I want to have just one table.
---- First Table
select f. date as Date, f.value as Month1
from
(
select b.date as date, sum(b.value) as value
from business bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus2 b on b.id = buc.id
where ct.id = 1
and b.value <> 0
and b.date between #start and #actual
and bu.name = #bu_name
group by b.date, b.value
union all
select b5.date as date, sum(b5.value) as value
from bus bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus3 b5 on b5.id = buc.id
where ct.id = 1
and b5.value <> 0
and b5.date between #nextM and #endM
and bu.name = #bu_name
group by b5.date, b5.value
) as f
---- Second Table
select f1. date as Date, f1.value as Month2
from
(
select b.date as date, sum(b.value) as value
from business bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus2 b on b.id = buc.id
where ct.id = 1
and b.value <> 0
and b.date between #start and #actual
and bu.name = #bu_name
group by b.date, b.value
union all
select b5.date as date, sum(b5.value) as value
from bus bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus3 b5 on b5.id = buc.id
where ct.id = 1
and b5.value <> 0
and b5.date between #nextM and #endM
and bu.name = #bu_name
group by b5.date, b5.value
) as f1
The actual output for first table is:
Date Month1
2015-01-01 23
2015-01-01 77
and for second:
Date Month2
2015-01-01 88
2015-01-01 90
All I want is to merge this 2 tables to look like
Date Month1 Date Month2
2015-01-01 23 2015-01-01 77
2015-01-01 28 2015-01-01 787
As I said in my comment, a simple join should do the trick. Something like:
SELECT *
FROM
(
select b.date as date, sum(b.value) as value
from business bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus2 b on b.id = buc.id
where ct.id = 1
and b.value <> 0
and b.date between #start and #actual
and bu.name = #bu_name
group by b.date, b.value
union all
select b5.date as date, sum(b5.value) as value
from bus bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus3 b5 on b5.id = buc.id
where ct.id = 1
and b5.value <> 0
and b5.date between #nextM and #endM
and bu.name = #bu_name
group by b5.date, b5.value
) as f
LEFT JOIN (
select b.date as date, sum(b.value) as value
from business bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus2 b on b.id = buc.id
where ct.id = 1
and b.value <> 0
and b.date between #start and #actual
and bu.name = #bu_name
group by b.date, b.value
union all
select b5.date as date, sum(b5.value) as value
from bus bu
join bus_cat buc on buc.id = bu.id
join cat ct on ct.id = buc.type_id
join bus3 b5 on b5.id = buc.id
where ct.id = 1
and b5.value <> 0
and b5.date between #nextM and #endM
and bu.name = #bu_name
group by b5.date, b5.value
) as f1
ON f.date = f1.date
edit
By the way, this query can be simplified, looks like there are many similarities in the queries.

Self join issue

I have a table called tblAccInfo, below is the table data.
I need output like below.
Input
PolicyNumber BankAc StorageDate VerNum
6003210400 123 2012-01-01 1
6003210400 164 2012-01-03 2
6003210400 860 2012-01-05 3
6004317654 301 2012-02-05 1
6004317654 615 2012-03-01 2
6004317654 253 2012-03-12 3
6004317654 887 2012-04-03 4
OUTPUT
PolicyNumber IntialBankAc IntialSDate VerNum LatestBankAc LatestSDate VerNum
6003210400 123 2012-01-01 1 860 2012-01-05 3
6004317654 301 2012-02-05 1 887 2012-04-03 4
I have tried with below self join, but did not succeeded. Please help me out in this.
Select DISTINCT
P.PolicyNumber,
P.BankAc [IntialBankAc],
P.StorageDate IntialSDate],
P.VerNum,
P1.BankAc [LatestBankAc],
P1.StorageDate [LatestSDate],
P1.VerNum
FROM tblAccInfo P
INNER JOIN tblAccInfo P1
ON P1.PolicyNumber=P.PolicyNumber
AND (P.BankAc<>P1.BankAc AND P.StorageDate<>P1.StorageDate AND P.VerNum<>P1.VerNum)
Try this:
SELECT
T1.PolicyNumber,
T2.BankAc AS IntialBankAc,
T2.StorageDate AS IntialSDate,
T2.VerNum AS InitalVerNum,
T3.BankAc AS LatestBankAc,
T3.StorageDate AS LatestSDate,
T3.Vernum AS LatestVerNum
FROM
(
SELECT
PolicyNumber,
MIN(VerNum) AS MinVerNum,
MAX(VerNum) AS MaxVerNum
FROM tblAccInfo
GROUP BY PolicyNumber
) AS T1
JOIN tblAccInfo AS T2
ON T1.PolicyNumber = T2.PolicyNumber
AND T1.MinVerNum = T2.VerNum
JOIN tblAccInfo AS T3
ON T1.PolicyNumber = T3.PolicyNumber
AND T1.MaxVerNum = T3.VerNum
See it working online: sqlfiddle
DECLARE #x TABLE
(
PolicyNumber VARCHAR(32),
BankAc INT,
StorageDate DATE,
VerNum INT
);
INSERT #x VALUES
('6003210400','123','2012-01-01',1),
('6003210400','164','2012-01-03',2),
('6003210400','860','2012-01-05',3),
('6004317654','301','2012-02-05',1),
('6004317654','615','2012-03-01',2),
('6004317654','253','2012-03-12',3),
('6004317654','887','2012-04-03',4);
WITH x AS
(
SELECT PolicyNumber, BankAc, StorageDate, VerNum,
f = ROW_NUMBER() OVER (PARTITION BY PolicyNumber ORDER BY VerNum),
l = ROW_NUMBER() OVER (PARTITION BY PolicyNumber ORDER BY VerNum DESC)
FROM #x
)
SELECT
x.PolicyNumber,
InitialBankAc = x.BankAc,
InitialSDate = x.StorageDate,
InitialVerNum = x.VerNum,
LatestBankAc = x2.BankAc,
LatestSDate = x2.StorageDate,
LatestVerNum = x2.VerNum
FROM x INNER JOIN x AS x2
ON x.PolicyNumber = x2.PolicyNumber
WHERE x.f = 1 AND x2.l = 1
ORDER BY x.PolicyNumber;
not tested - but should give you the idea. (There may be a more efficient way of doing this - it was just the approach that jumped out at me.)
select initial.policynumber
,initial.initialbankaccoutn
,initial.initialstoragedate
,initial.intialvernum
,final.latestbankaccount
,final.lateststoragedate
,final.latestvernum
from
(select a.policynumber, a.bankaccount as initialbankaccount, a.storagedate as initialstoragedate, a.vernum as initialvernum
from tblAccInfo a1
inner join (select min(storagedate) as storagedate, policynumber
from tblAccInfo
group by policynumber) a
on a.policynumber = a1.policynumber
and a.storagedate = a1.storagedate) initial
inner join
(select b.policynumber, b.bankaccount as latestbankaccount, b.storagedate as lateststoragedate, b.vernum as latestvernum
from tblAccInfo b1
inner join (select min(storagedate) as storagedate, policynumber
from tblAccInfo
group by policynumber) b
on a.policynumber = b1.policynumber
and a.storagedate = b1.storagedate) final
on final.policynumber = initial.policynumber