Not getting data from Second table - sql

''hi all
''query is working but i am not getting data from BD table ( B_Detail )
''What am i doing wrong..??
SELECT CM.CM_Date AS Cdate, CM.C_MemoNo AS CmNo,0 as BookDate, 0 as LR_No,
CM.CM_Total as CMAmt, 0 as Amt_Rcvd, 0 as ChqDDNo, 0 as ChqDDdate, 0 as Acc_Typ,
0 as RcptNo,0 as MemoNo, 0 as M_Date, CM.CNee as conName
from (CMemo as CM
INNER JOIN ClientLedger ON (ClientLedger.CName = CM.CNee))
UNION ALL
Select 0 as Rcpt_Date, 0 as CmNo, BD.Bdate as BookDate, BD.BNo as LR_No,
0 as CM_Total, 0 as Amt_Rcvd, 0 as ChqDDNo, 0 as ChqDDdate, 0 as Acc_Typ,
0 as RcptNo,BD.CST as MNo, BD.GRDate as M_Date, BD.Consignee
from (B_Detail BD
INNER JOIN Receipt_CLNT CM ON (CM.CNee = BD.Consignee))
UNION ALL
SELECT Receipt_CLNT.Rcpt_Date, 0 as CmNo, 0 as BookDate, 0 as LR_No,
0 as CM_Total, Receipt_CLNT.Amt_Rcvd as RcptAmt,Receipt_CLNT.ChqDDNo as RefNo,
Receipt_CLNT.ChqDDdate as RefDate, Receipt_CLNT.Amt_Mode as Mode,
Receipt_CLNT.RcptNo as RcptNo, 0 as MemoNo, 0 as MDate, Receipt_CLNT.G_Name
from Receipt_CLNT
ORDER BY Cdate;

If you simplify the question to just the problem part does it still not return data?
Select 0 as Rcpt_Date, 0 as CmNo, BD.Bdate as BookDate, BD.BNo as LR_No,
0 as CM_Total, 0 as Amt_Rcvd, 0 as ChqDDNo, 0 as ChqDDdate, 0 as Acc_Typ,
0 as RcptNo,BD.CST as MNo, BD.GRDate as M_Date, BD.Consignee
from (B_Detail BD
INNER JOIN Receipt_CLNT CM ON (CM.CNee = BD.Consignee))
If so then the join (being an inner join) is not matching any keys.
CM.CNee = BD.Consignee

Related

SQL Select with joins and calculate percentage

I have three tables and I'm trying to make a select statement to give me a result like the one below
Teams:
ID Name
1 A
2 B
3 C
Players:
ID Name TeamID
1 P1 1
2 P2 1
3 P3 2
Goals: (goaltype: H for home, A for away, T for training)
ID PID goaltype
1 1 A
2 1 A
3 1 H
4 2 A
5 2 H
6 3 A
7 3 T
Result will be Like:
Team totalGoals home away trainig percentage[(home/total)*100]
A 5 2 3 0 40%
B 2 0 1 1 0
C 0 0 0 0 0
This is my current query:
select t.name,
count(g.id) as totalGoals,
sum(case when g.GTYPE = 'H' then 1 else 0 end) as home,
sum(case when g.GTYPE = 'A' then 1 else 0 end) as away,
sum(case when g.GTYPE = 'T' then 1 else 0 end) as training,
--(home/totalGoals) as percentage
from teams t
left join players p on p.TeamID = t.id
left join goals g on g.pid = p.id
group by t.name
You can use conditional aggregation to get the results you want:
SELECT t.Name AS Team,
COUNT(g.goaltype) AS totalGoals,
SUM(CASE WHEN g.goaltype = 'H' THEN 1 ELSE 0 END) AS home,
SUM(CASE WHEN g.goaltype = 'A' THEN 1 ELSE 0 END) AS away,
SUM(CASE WHEN g.goaltype = 'T' THEN 1 ELSE 0 END) AS training,
CASE WHEN COUNT(g.goaltype) = 0 THEN 0
ELSE 100.0 * SUM(CASE WHEN g.goaltype = 'H' THEN 1 ELSE 0 END) /
COUNT(g.goaltype)
END AS percentage
FROM Teams t
LEFT JOIN Players p ON p.TeamID = t.ID
LEFT JOIN Goals g ON g.PID = p.ID
GROUP BY t.Name
ORDER BY t.Name
Output:
team totalgoals home away training percentage
A 5 2 3 0 40
B 2 0 1 1 0
C 0 0 0 0 0
Demo on SQLFiddle

Get COUNT with a condition from a joined table

I have a table SyncHistory:
SyncHistoryId SyncType SyncDateTime
-----------------------------------------------------
55 1 2017-11-28 09:30:51.810
56 1 2017-11-28 10:30:32.123
And then another table SyncDetails:
SyndDetailId SyncHistoryId ItemId ItemCreated ItemChanged
---------------------------------------------------------------------------
98 55 12345 1 0
99 55 23183 1 0
100 55 87687 0 1
101 55 23234 0 0
102 55 23222 0 0
103 56 9928 1 0
What I'm trying to do is create a query that gives me this:
Sync Data New Existing & Changed Existing & Not Changed
---------------------------------------------------------------------------
11/28/2017 9:30am 2 1 2
11/28/2017 10:30am 1 0 0
This is what I'm trying:
SELECT
sh.SyncHistoryId
, sh.SyncDateTime
, count(sd1.SyncDetailId) AS Created
, count(sd2.SyncDetailId) AS ExistingChanged
, count(sd3.SyncDetailId) AS ExistingNotChanged
FROM
SyncHistory sh
LEFT JOIN SyncDetails sd1 ON sh.SyncHistoryId = sd1.SyncHistoryId AND sd1.ItemCreated = 1 AND sd1.ItemChanged = 0
LEFT JOIN SyncDetails sd2 ON sh.SyncHistoryId = sd2.SyncHistoryId AND sd2.ItemCreated = 0 AND sd2.ItemChanged = 1
LEFT JOIN SyncDetails sd3 ON sh.SyncHistoryId = sd3.SyncHistoryId AND sd3.ItemCreated = 0 AND sd3.ItemChanged = 0
WHERE
sh.SyncType = 1
GROUP BY
sh.SyncHistoryId
, sh.SyncDateTime
ORDER BY
sh.SyncDateTime DESC
But, none of the resulting counts are accurate. I'm doing something wrong, but not sure what.
SELECT h.SyncDateTime,
SUM(case when d.ItemCreated = 1 then 1 else 0 end) as New,
SUM(case when d.ItemChanged = 1 then 1 else 0 end) as [Existing & Changed],
SUM(case when d.ItemCreated = 0 and d.ItemChanged = 0 then 1 else 0 end) as [Existing & Not Changed]
FROM SyncHistory h
INNER JOIN SyncDetails d ON h.SyncHistoryId = d.SyncHistoryId
GROUP BY h.SyncDateTime
You only need to JOIN to the details table once. You can get your counts from that through aggregation:
SELECT
CONVERT(VARCHAR(16), SH.SyncDateTime, 120) AS SyncTime,
SUM(CASE WHEN SD.ItemCreated = 1 AND SD.ItemChanged = 0 THEN 1 ELSE 0 END) AS New,
SUM(CASE WHEN SD.ItemCreated = 0 AND SD.ItemChanged = 1 THEN 1 ELSE 0 END) AS ExistingAndChanged,
SUM(CASE WHEN SD.ItemCreated = 0 AND SD.ItemChanged = 0 THEN 1 ELSE 0 END) AS ExistingAndNotChanged
FROM
SyncHistory SH
LEFT OUTER JOIN SyncDetails SD ON SD.SyncHistoryID = SH.SyncHistoryID
GROUP BY
CONVERT(VARCHAR(16), SH.SyncDateTime, 120)
You weren't clear on how the grouping/datetime should be determined. What I have is by the minute. If it's supposed to be by the hour on the 1/2 hour mark or something else then you'll need to change that part of the query in the GROUP BY and the first column of the SELECT.
Another solution. I hope it will work - no CASE, no subquery:
SELECT
sh.SyncHistoryId
,sh.SyncDateTime
,COUNT( NULLIF( sd.ItemCreated, 0 ) ) AS Created
,COUNT( NULLIF( sd.ItemCreated, 1 ) + NULLIF( sd1.ItemChanged, 0 ) ) AS ExistingChanged
,COUNT( NULLIF( sd.ItemCreated, 1 ) + NULLIF( sd1.ItemChanged, 1 ) ) AS ExistingNotChanged
FROM
SyncHistory sh JOIN SyncDetails sd ON sh.SyncHistoryId = sd.SyncHistoryId
WHERE
sh.SyncType = 1
GROUP BY
sh.SyncHistoryId
,sh.SyncDateTime
ORDER BY
sh.SyncDateTime DESC
I hope subquery is not forbidden:
SELECT
sh.SyncHistoryId
,sh.SyncDateTime
,(SELECT COUNT(*) FROM SyncDetails sd WHERE sh.SyncHistoryId = sd.SyncHistoryId AND sd.ItemCreated = 1 AND sd1.ItemChanged = 0) AS Created
,(SELECT COUNT(*) FROM SyncDetails sd WHERE sh.SyncHistoryId = sd.SyncHistoryId AND sd.ItemCreated = 0 AND sd1.ItemChanged = 1) AS ExistingChanged
,(SELECT COUNT(*) FROM SyncDetails sd WHERE sh.SyncHistoryId = sd.SyncHistoryId AND sd.ItemCreated = 0 AND sd1.ItemChanged = 0) AS ExistingNotChanged
FROM
SyncHistory sh
WHERE
sh.SyncType = 1
ORDER BY
sh.SyncDateTime DESC

TSQL: how do i show 0.00 totals for this column

I have a Department table with 15 different departments. I want my query to show some totals for a certain project. In this particular project there are 3 departments that are working on it and have totals for various things. My current query does show the totals for those three departments. However, i also want to show all the other departments but just have zeros in the totals columns for those departments. Those departments did not have anything to do with this project but still need to show them with zero totals. Here is my query that results in three rows of data. Disciplines is the table with all my departments. Project_Disciplines are those that are actually working on the project
SELECT
T.NAme
,ISNULL(CAST(t.EngHours AS DECIMAL(15,0)),0) AS EngHours
,ISNULL(SUM(t.EngBlendedRate),0) as EngRate
,ISNULL(CAST(t.EngHours * SUM(t.EngBlendedRate) AS DECIMAL(15,0)),0) AS EngDollars
,ISNULL(CAST(t.DesignHours AS DECIMAL(15,0)),0) AS DesignHours
,ISNULL(sum(t.DsgBlendedRate),0) AS DesignRate
,ISNULL(CAST(t.DesignHours * SUM(t.DsgBlendedRate) AS DECIMAL(15,0)),0) AS DesignDollars
,ISNULL(t.EngHours + t.DesignHours,0) AS TotalHours
,ISNULL(CAST(CAST((t.EngHours * SUM(t.EngBlendedRate)) + (t.DesignHours * SUM(t.DsgBlendedRate)) AS DECIMAL (18,2)) / CAST(NULLIF(t.EngHours + t.DesignHours,0) AS DECIMAL(18,2)) AS DECIMAL (18,2)),0) AS TotalRate
,CAST(ISNULL((t.EngHours * SUM(t.EngBlendedRate)),0) + ISNULL((t.DesignHours * SUM(t.DsgBlendedRate)),0) AS DECIMAL(15,0)) AS TotalDollars
,ISNULL(MAX(case when OA.Code = 'Travel' then OA.Cost end),0) Travel
,ISNULL(MAX(case when OA.Code = 'Equipment' then OA.Cost end),0) Equipment
,ISNULL(MAX(case when OA.Code = 'Subcontract' then OA.Cost end),0) Subcontract
,ISNULL(MAX(case when OA.Code = 'Other' then OA.Cost end),0) Other
,ISNULL(MAX(case when OA.Code = 'Markups' then OA.Cost end),0) Markups
,CAST(ISNULL((t.EngHours * SUM(t.EngBlendedRate)),0) + ISNULL((t.DesignHours * SUM(t.DsgBlendedRate)),0) AS DECIMAL(15,0))
+ ISNULL(MAX(case when OA.Code = 'Travel' then OA.Cost end),0)
+ ISNULL(MAX(case when OA.Code = 'Equipment' then OA.Cost end),0)
+ ISNULL(MAX(case when OA.Code = 'Subcontract' then OA.Cost end),0)
+ ISNULL(MAX(case when OA.Code = 'Other' then OA.Cost end),0)
+ ISNULL(MAX(case when OA.Code = 'Markups' then OA.Cost end),0) AS EstimateTotal
FROM
(SELECT c.id, x.Name,
ISNULL(CASE WHEN f.team_type_id = 1 OR f.team_type_id = 3
THEN
CAST(f.POH * (d.HourlyRate * (1-(r.Discount/100))/100) AS DECIMAL(8,2))
END,0) AS EngBlendedRate ,
ISNULL(CASE WHEN f.team_type_id = 2 OR f.team_type_id = 4
THEN
ISNULL(CAST(f.POH * (d.HourlyRate * (1-(r.Discount/100))/100) AS DECIMAL(8,2)),0) END,0) AS DsgBlendedRate
,ISNULL(CAST(SUM((b.qty * b.unit_rate)* b.Eng_RPQ /100) AS DECIMAL(8,1)),0) AS [EngHours]
,ISNULL(CAST(SUM((b.qty * b.unit_rate)* b.Design_RPQ /100) AS DECIMAL(8,1)),0) AS [DesignHours]
FROM Project p
INNER JOIN Project_Disciplines pd on p.id = pd.project_id
INNER JOIN Discipline x on x.id = pd.Disc_id
INNER JOIN Activity c on c.discipline_id = x.id
INNER JOIN Activity_Details b ON b.activity_id = c.id
INNER JOIN Team f on f.activity_id = c.id
INNER JOIN SOF_Details d on d.id = f.sof_detail_id
INNER JOIN Rate r on r.projectid = p.id
WHERE p.id = 19
GROUP BY c.id, x.Name,
f.team_type_id
, f.POH,d.HourlyRate,r.Discount
) AS T
LEFT OUTER JOIN (
SELECT a.activity_id, c.Code
,CAST(Sum(a.Rate * a.Qty)AS DECIMAL(18,2)) AS COST
FROM Other_Activity a
INNER JOIN Activity b on a.activity_id = b.id
INNER JOIN EXPENSE_Codes c on a.expense_code_id = c.id
WHERE b.project_id = 19
GROUP BY a.activity_id, c.Code) AS OA ON OA.activity_id = T.id
GROUP BY T.Name, t.EngHours, t.DesignHours
Results
NAme EngHours EngRate EngDollars DesignHours DesignRate DesignDollars TotalHours TotalRate TotalDollars Travel Equipment Subcontract Other Markups EstimateTotal
Architechtural 81 110.73 8947 237 78.85 18711 318.1 86.95 27658 0.00 0.00 0.00 0.00 0.00 27658.00
Concrete 3014 423.72 1277092 2136 357.96 764603 5150.0 396.45 2041695 60.00 45.00 0.00 325.00 0.00 2042125.00
Structural 903 104.98 94744 1351 0.00 0 2253.0 42.05 94744 0.00 0.00 0.00 0.00 0.00 94744.00
I would like to show the other departments also with zeros
NAme EngHours EngRate EngDollars DesignHours DesignRate DesignDollars TotalHours TotalRate TotalDollars Travel Equipment Subcontract Other Markups EstimateTotal
Architechtural 81 110.73 8947 237 78.85 18711 318.1 86.95 27658 0 0 0 0 0 27658
Concrete 3014 423.72 1277092 2136 357.96 764603 5150 396.45 2041695 60 45 0 325 0 2042125
Structural 903 104.98 94744 1351 0 0 2253 42.05 94744 0 0 0 0 0 94744
Mechanical 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Piping 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Process 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Civil 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Electrical 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Project Admin 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
C&A 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Estimating 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Procurement 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
I assume the Activity and Activity_Details tables do not have any data for those departments. You should make them and any other table without data for all departments be connected as left joins.
You can run the subquery labeled T on a standalone basis and make sure that all your departments are on the list. Without knowing the table structure, you might have to reorder the tables in the subquery T to make "Discipline" come first, then left join everything else that is not guaranteed to have info on all departments

Need Help on Oracle Select Query

I am finding difficulty to frame a select query.
PFB, for the table and corresponding data:
ID DLS MATCH_STATUS LAST_UPDATE_TIME BO CH FT
1 0 0 09-07-2013 00:00:00 IT TE NA
1 1 1 09-07-2013 00:01:01 IT TE NA
2 0 0 09-07-2013 10:00:00 IP TE NA
3 0 0 09-07-2013 11:00:00 IT YT NA
3 2 2 09-07-2013 11:01:00 IT YT NA
Here
Match_Status 0-->Initial Record
1-->Singel Match
2-->Multi Match
For every record there will be a initial entry with match_status 0 and subsequent matching process end other number such as 1,2 will be update.
I am trying to retrieve records such as total record , waiting match ,single match and multi match group by BO, CH and FT
Below is the expected out put:
BO CH FT TOTAL_RECORD AWAITNG_MATCH SINGLE_MATCH MULTI_MATCH
IT TE NA 1 0 1 0
IP TE NA 1 1 0 0
IT YT NA 1 0 0 2
I have tried below query :
select BO,CH,FT,sum(case when match_status=0 then 1 else 0 end) as TOTAL_RECORD,
sum(case when match_status = 0 then 1 else 0 end) as AWAITING_MATCH,
sum(case when match_status = 1 then 1 else 0 end) as SINGLE_MATCH,
sum(case when match_status = 2 then 1 else 0 end) as MULTI_MATCH from
table1 where last_update_time >= current_timestamp-1
group by BO,CH,FT;
problem with the above query is, awaiting_match is getting populated same as total record as I understand because of match_status=0
Similarly I tried with
select BO,CH,FT,sum(case when match_status=0 then 1 else 0 end) as TOTAL_RECORD,
select (sum(case when t1.ms=0 then 1 else 0 end) from
(select max(match_status) as ms from table1 where last_update_time >= current_timestamp-1 group by id)t1) )awaiting_match,
sum(case when match_status = 1 then 1 else 0 end) as SINGLE_MATCH,
sum(case when match_status = 2 then 1 else 0 end) as MULTI_MATCH from
table1 where last_update_time >= current_timestamp-1
group by BO,CH,FT;
problem with the approach is awaiting_match is getting populated with the same value for subsequent row entry.
Please help me with a suitable query for the desired format.
Thanks a lot in advance.
It seems that you want the last match status. I am guessing that this is actually the maximum of the statuses. If so, the following solves the problem by first grouping on id and then doing the grouping to summarize:
select BO, CH, FT,
count(*) as TOTAL_RECORD,
sum(case when lastms = 0 then 1 else 0 end) as AWAITING_MATCH,
sum(case when lastms = 1 then 1 else 0 end) as SINGLE_MATCH,
sum(case when lastms = 2 then 1 else 0 end) as MULTI_MATCH
from (select id, bo, ch, ft, MAX(match_status) as lastms
from table1
where last_update_time >= current_timestamp-1
group by id, bo, ch, ft
) t
group by BO, CH, FT;
If you actually want the last update to provide the status for the id, then you can use row_number() to enumerate the rows for each id, order by update time descending, and choose the first one:
select BO, CH, FT,
count(*) as TOTAL_RECORD,
sum(case when lastms = 0 then 1 else 0 end) as AWAITING_MATCH,
sum(case when lastms = 1 then 1 else 0 end) as SINGLE_MATCH,
sum(case when lastms = 2 then 1 else 0 end) as MULTI_MATCH
from (select id, bo, ch, ft, match_status,
ROW_NUMBER() over (partition by id order by last_update_time desc) as seqnum
from table1
where last_update_time >= current_timestamp-1
) t
where seqnum = 1
group by BO, CH, FT;

Fetch the total from the result of a query

The query i am using is
select convert(varchar(10), sales.saledate, 103) [SaleDate], SUM(sales.Domestic) [Domestic], SUM(sales.Export) [Export], SUM(sales.Import) [Import],
SUM(sales.Value) [Value], Sum(sales.Cancelled) [Cancelled], sum(sales.cancelledValue) [CancelledValue], SUM(sales.totalValue) [TotalValue]
from
(
select max(j.SaleDate) SaleDate,
case when max(oc.Code) = 'AU' and max(dc.Code) = 'AU' then 1 else 0 end [Domestic],
case when max(oc.Code) = 'AU' and max(dc.Code) <> 'AU' then 1 else 0 end [Export],
case when max(oc.Code) <> 'AU' and max(dc.Code) = 'AU' then 1 else 0 end [Import],
1 [Total],
max(ic.Total) [Value],
case when max(c.CancelDate) is not null then 1 else 0 end [Cancelled],
case when max(c.CancelDate) is not null then max(ic.Total) else 0 end [CancelledValue],
case when max(c.CancelDate) is null then max(ic.Total) else 0 end [TotalValue]
from invoices i
left join Jobs j on i.JobKey = j.JobKey
inner join tasks t on j.jobkey = t.jobkey
inner join Consignments c on t.TaskKey = c.consignmentkey
inner join places op on c.originplacekey = op.placekey
inner join places dp on c.destinationplacekey = dp.placekey
inner join places oC on dbo.ParentPlaceKey(c.originPlaceKey) = oc.placekey
inner join places dC on dbo.ParentPlaceKey(c.destinationplacekey) = dc.placekey
left join (select consignmentKey, sum(Value) [Value] from ConsignmentItems ci group by consignmentkey ) ci on ci.ConsignmentKey = c.ConsignmentKey
left join (select invoicekey, sum(case when ci.ChargeItemKey = 'FRT_SLL' then oc.Value else 0 end) [Freight],
sum(case when ci.ChargeItemKey = 'WTY_SLL' then oc.Value else 0 end) [Warranty],
sum(case when ci.ChargeType = 4 then oc.Value else 0 end) [Total] from InvoiceCharges ic
left join OptionCharges oc on ic.OptionChargeKey = oc.OptionChargeKey
left join ChargeItems ci on oc.ChargeItemKey = ci.ChargeItemKey
group by invoicekey
) ic on ic.InvoiceKey = i.InvoiceKey
where
j.SaleDate >= '01-Apr-2013' and j.SaleDate <= '10-May-2013'
and
j.operationalstorekey = dbo.StoreCode('AU-WEB')
and j.saledate is not null and SelectedOptionKey is not null
group by j.jobkey
) sales
group by convert(varchar(10), sales.saledate, 103)
order by max(sales.saledate)
The result of a sql query is
SaleDate Domestic Export Import Value Cancelled CancelledValue Totalvalue
11/04/2013 1 0 0 47.200 0 0.0000 47.2000
16/04/2013 6 0 0 249.750 0 0.0000 249.7500
22/04/2013 0 1 0 223.480 0 0.0000 223.4800
23/04/2013 0 3 0 670.440 0 0.0000 670.4400
I want result like (want to add the TOTALS at the end)
SaleDate Domestic Export Import Value Cancelled CancelledValue Totalvalue
11/04/2013 1 0 0 47.200 0 0.0000 47.2000
16/04/2013 6 0 0 249.750 0 0.0000 249.7500
22/04/2013 0 1 0 223.480 0 0.0000 223.4800
23/04/2013 0 3 0 670.440 0 0.0000 670.4400
TOTALS 7 4 0 1190.432 0 0 1190.432
Can anyone please tell me how to achieve this in above query, i am trying with temp tables which i dont want.
Thanks.
You can achieve this by adding an UNION at the end of your result. Something like:
... order by max(sales.saledate)
UNION
(SELECT "TOTALS", SUM(sales.Domestic) AS Domestic, SUM(sales.Export) AS Export,
SUM(sales.Import) AS Import, SUM(sales.Value) [Value], Sum(sales.Cancelled) AS Cancelled, sum(sales.cancelledValue) AS CancelledValue, SUM(sales.totalValue) AS TotalValue
FROM "your_big_query"...
WHERE ...
)
And this time remove the group by convert(varchar(10), sales.saledate, 103)
EDIT
Or you can use the GROUP BY Modifiers try to use this in the GROUP BY statement:
group by convert(varchar(10), sales.saledate, 103) WITH ROLLUP
You can read the official documentation here with some examples too.
Hope this works!!