Is there any way to write this query without using WITH Clause - sql

Screenshot of table account:
[]
Screenshot of table trandetails:
[
Problem: Write a query to display the total number of withdrawals and total number of deposits being done by customer whose registration is C00001. Give the count an alias name of Trans_Count.
I want to reduce line of code for the above question
I have written this query
Code:
with t as
(
select acnumber,transaction_type,count(transaction_type) as trans_type
from trandetails as t
group by transaction_type,acnumber
)
,c as
(
select c.custid,c.acnumber
from account as c
where custid like 'C00001'
)
select c.custid,t.transaction_type,t.trans_type
from t inner join c on c.acnumber = t.acnumber

SELECT c.custid,
t.transaction_type,
t.trans_type
FROM account AS c
INNER JOIN(
SELECT acnumber,
transaction_type,
COUNT(transaction_type) AS trans_type
FROM trandetails
GROUP BY transaction_type,
acnumber ) t ON c.acnumber = t.acnumber
WHERE c.custid LIKE 'C00001';
If acnumber is unique in account, then it would be further simpler:
SELECT c.custid,
t.transaction_type,
COUNT(t.transaction_type) AS trans_type
FROM account AS c
INNER JOIN trandetails AS t ON c.acnumber = t.acnumber
WHERE c.custid LIKE 'C00001'
GROUP BY c.custid,
t.transaction_type;

Try this query
SELECT c.custid, t.transaction_type, t.trans_type
FROM (SELECT acnumber, transaction_type, COUNT(transaction_type) AS trans_type
FROM trandetails
GROUP BY transaction_type, acnumber
) t
INNER JOIN (SELECT custid, acnumber
FROM account
WHERE custid LIKE 'C00001'
) c
ON c.acnumber = t.acnumber

See if that is what you want:
select a.custid
,t.transaction_type
,sum(t.transaction_amount) amount
from account a
,trandetails t
where t.acnumber = a.acnumber
and a.custid = 'C00001'
group by a.custid
,t.transaction_type;

Here is an example with conditional aggregation:
select a.custid,
sum(case when d.transaction_type = 'Deposit' then 1 end) as DepositCount,
sum(case when d.transaction_type = 'Withdrawal' then 1 end) as WithdrawalCount,
from account a
join trandetails d on a.acnumber = d.acnumber
where a.custid = 'C00001'
group by a.custid

You can always use subquery insted of CTE
select c.custid,
t.transaction_type,
t.trans_type
from account c
inner join (
select s.acnumber,
s.transaction_type,
count(s.transaction_type) as trans_type
from trandetails as s
group by s.transaction_type,
s.acnumber) t on c.acnumber = t.acnumber
where c.custid = 'C00001'
Probably you have to use either s.custid = 'C00001' or something like that s.custid like '%C00001%'. like is used to search inside of some string, not for direct comparision for equality.

Tip 1: Avoid subquery if possible
Tip 2: Do not use LIKE clause if not required - in your case seems that '=' will do the job - here is a small testing sample:
DECLARE #account TABLE (
custid VARCHAR(20),
acnumber VARCHAR(20)
)
DECLARE #trandetails TABLE (
acnumber VARCHAR(20),
transaction_type VARCHAR(20)
)
INSERT INTO
#account
VALUES
('C00001', 'A00001'),
('C00002', 'A00002')
INSERT INTO
#trandetails
VALUES
('A00001', 'Withdrawal'),
('A00001', 'Deposit'),
('A00002', 'Deposit')
SELECT
acc.custid,
td.transaction_type,
count(td.transaction_type) AS trans_cnt
FROM
#account acc
INNER JOIN #trandetails td
ON acc.acnumber = td.acnumber
WHERE
acc.custid = 'C00001'
GROUP BY
acc.custid,
td.acnumber,
td.transaction_type

Related

Query for count and distinct

I should make a report in T-SQL from several table.
I can join all the table needed but after I don't know excatly how to get my information.
Explanation :
I've got the following table :
Tbl_User (UserId, Username)
Tbl_Customer (CustomeriD, CustomerName)
Tbl_DocA (DocId, CustomerID, DateCreate, DateAdd, UseriD)
Tbl_DocB (DocId, CustomerID, DateCreate, DateAdd, UseriD)
Tbl_DocC (DocId, CustomerID, DateCreate, DateAdd, UseriD)
I am trying to get a report like this :
After I can get this, the idea is to have a filter with the date in SQL reporting.
You can union all the document tables together and join users and customers on it.
SELECT Customer.CustomerID
,Customer.CustomerName
,COUNT(CASE WHEN DocType = 'A' THEN 1 END) AS doc_a_total
,COUNT(CASE WHEN DocType = 'B' THEN 1 END) AS doc_b_total
,COUNT(CASE WHEN DocType = 'C' THEN 1 END) AS doc_c_total
,COUNT(CASE WHEN DocType = 'A' AND user.username ='azerty' THEN 1 END) AS doc_a_made_by_azerty
,COUNT(CASE WHEN DocType = 'B' AND user.username ='azerty' THEN 1 END) AS doc_b_made_by_azerty
,COUNT(CASE WHEN DocType = 'C' AND user.username ='azerty' THEN 1 END) AS doc_c_made_by_azerty
FROM (
(SELECT 'A' AS DocType, * FROM Tbl_DocA)
UNION ALL
(SELECT 'B' AS DocType, * FROM Tbl_DocB)
UNION ALL
(SELECT 'C' AS DocType, * FROM Tbl_DocC)
) AS docs
JOIN Tbl_User AS user ON user.UserId = docs.UseriD
JOIN Tbl_Customer AS Customer ON Customer.CustomeriD = docs.CustomeriD
GROUP BY Customer.CustomerID , Customer.CustomerName
You can use common table expressions to get the count for each report type per customer, with conditional aggregation for reports made by a specific user, and join them to the customers table.
Something like this should get you the desired results:
DECLARE #UserId int = 1; -- or whatever the id of the user you need
WITH CTEDocA AS
(
SELECT CustomerID
, COUNT(DocId) As NumberOfReports
, COUNT(CASE WHEN UserId = #UserId THEN 1 END) As NumberOfReportsByUserAzerty
FROM Tbl_DocA
GROUP BY CustomerID
), CTEDocB AS
(
SELECT CustomerID
, COUNT(DocId) As NumberOfReports
, COUNT(CASE WHEN UserId = #UserId THEN 1 END) As NumberOfReportsByUserAzerty
FROM Tbl_DocB
GROUP BY CustomerID
), CTEDocC AS
(
SELECT CustomerID
, COUNT(DocId) As NumberOfReports
, COUNT(CASE WHEN UserId = #UserId THEN 1 END) As NumberOfReportsByUserAzerty
FROM Tbl_DocC
GROUP BY CustomerID
)
SELECT cust.CustomeriD
,cust.CustomerName
,ISNULL(a.NumberOfReports, 0) As NumberOfDocA
,ISNULL(a.NumberOfReportsByUserAzerty, 0) As NumberOfDocAByAzerty
,ISNULL(b.NumberOfReports, 0) As NumberOfDocB
,ISNULL(b.NumberOfReportsByUserAzerty, 0) As NumberOfDocBByAzerty
,ISNULL(c.NumberOfReports, 0) As NumberOfDocC
,ISNULL(c.NumberOfReportsByUserAzerty, 0) As NumberOfDocCByAzerty
FROM Tbl_Customer cust
LEFT JOIN CTEDocA As a
ON cust.CustomeriD = a.CustomerID
LEFT JOIN CTEDocA As b
ON cust.CustomeriD = b.CustomerID
LEFT JOIN CTEDocA As c
ON cust.CustomeriD = c.CustomerID
To filter by date you can add a where clause to each common table expresstion.
BTW, The fact that you have three identical tables for three document types suggest a bad database design.
If these tables are identical you should consider replacing them with a single table and add a column to that table describing the document type.
There are several ways to do this. One key feature needed is to count a particular user apart from the others. This is done with conditional aggregation. E.g.:
select
customerid,
count(*),
count(case when userid = <particular user ID here> then 1 end)
from tbl_doca
group by customerid;
Here is one possible query using a cross join to get the user in question once and cross apply to get the numbers.
select
c.customerid,
c.customername,
doca.total as doc_a_total,
doca.az as doc_a_by_azerty,
docb.total as doc_b_total,
docb.az as doc_b_by_azerty,
docc.total as doc_c_total,
docc.az as doc_c_by_azerty
from tbl_customer c
cross join
(
select userid from tbl_user where username = 'Azerty'
) azerty
cross apply
(
select
count(*) as total,
count(case when da.userid = azerty.userid then 1 end)n as az
from tbl_doca da
where da.customerid = c.customerid
) doca
cross apply
(
select
count(*) as total,
count(case when db.userid = azerty.userid then 1 end)n as az
from tbl_docb db
where db.customerid = c.customerid
) docb
cross apply
(
select
count(*) as total,
count(case when dc.userid = azerty.userid then 1 end)n as az
from tbl_docc dc
where dc.customerid = c.customerid
) docc
order by c.customerid;
Other options would be to replace the cross apply with left outer join and non-correlated subqueries or to put subqueries into the select clause.
Combining the totals for the documents is another method.
Then use conditional aggregation for the counts.
untested notepad scribble:
;WITH SPECIFICUSER AS
(
SELECT UseriD
FROM Tbl_User
WHERE UserName = 'azerty'
),
DOCTOTALS (
SELECT CustomeriD, UseriD, 'DocA' AS Src, COUNT(DocId) AS Total
FROM Tbl_DocA
GROUP BY CustomeriD, UseriD
UNION ALL
SELECT CustomeriD, UseriD, 'DocB', COUNT(DocId)
FROM Tbl_DocB
GROUP BY CustomeriD, UseriD
UNION ALL
SELECT CustomeriD, UseriD, 'DocC', COUNT(DocId)
FROM Tbl_DocC
GROUP BY CustomeriD, UseriD
)
SELECT
docs.CustomeriD,
cust.CustomerName,
SUM(CASE WHEN usrX.UseriD is not null AND docs.Src = 'DocA' THEN docs.Total ELSE 0 END) AS Total_DocA_userX,
SUM(CASE WHEN Src = 'DocA' THEN docs.Total ELSE 0 END) AS Total_DocA,
SUM(CASE WHEN usrX.UseriD is not null AND docs.Src = 'DocB' THEN docs.Total ELSE 0 END) AS Total_DocB_userX,
SUM(CASE WHEN Src = 'DocB' THEN docs.Total ELSE 0 END) AS Total_DocB,
SUM(CASE WHEN usrX.UseriD is not null AND docs.Src = 'DocC' THEN docs.Total ELSE 0 END) AS Total_DocC_userX,
SUM(CASE WHEN Src = 'DocC' THEN docs.Total ELSE 0 END) AS Total_DocC
FROM DOCTOTALS docs
LEFT JOIN Tbl_Customer cust ON cust.CustomeriD = docs.CustomeriD
LEFT JOIN Tbl_User usr ON usr.UseriD = docs.UseriD
LEFT JOIN SPECIFICUSER usrX ON usrX.UseriD = docs.UseriD
GROUP BY docs.CustomeriD, cust.CustomerName
ORDER BY docs.CustomeriD
Those long column names could be set on the report side

Easy Left Join SQL Syntax

New to SQL and want to complete a LEFT JOIN.
I have two seperate tables with the below code:
SELECT
StockCode, SalesOrder, SUM(OrderQty)
FROM
dbo.IopSalesPerf
WHERE
dbo.IopSalesPerf.CustRequestDate BETWEEN '2017-07-01' AND '2017-07-31'
AND EntrySystemTime = 1
AND Warehouse = '01'
AND StockCode = '001013'
GROUP BY
StockCode,SalesOrder
ORDER BY
StockCode ASC
SELECT
SalesOrder, SUM(NetSalesValue), SUM(QtyInvoiced)
FROM
ArTrnDetail
GROUP BY
SalesOrder
I would like to LEFT JOIN the last table onto the first using SalesOrder as the joining column. Can anyone assist with the syntax?
Simpliest way would be:
SELECT * FROM
(
SELECT StockCode,SalesOrder,sum(OrderQty)
FROM dbo.IopSalesPerf
WHERE dbo.IopSalesPerf.CustRequestDate between '2017-07-01' and '2017-07-31'
and EntrySystemTime = 1 and Warehouse = '01' and StockCode = '001013'
GROUP BY StockCode,SalesOrder
Order BY StockCode ASc
) AS A
LEFT JOIN
(
SELECT SalesOrder,sum(NetSalesValue),sum(QtyInvoiced)
FROM ArTrnDetail
Group by SalesOrder
) AS B
ON A.SalesOrder = B.SalesOrder

Select Inner Join Select in SQL

Hi i Have a Select Inner Join Statement it seems ok but i got error. this is my query
ALTER PROCEDURE [dbo].[POBalance] #PONumber nvarchar(50)
AS BEGIN
Select(
Select
A.Description,
C.qty as POqty,
B.QtyDelivered as PDQty,
case when A.partialflag ='false'
then '0'
else
A.qty end as Balance,
A.Unit,
A.Unitprice,
A.Partialflag
from tblPOdetails as A
Inner Join ( SELECT id, SUM(Qty) AS QtyDelivered
FROM dbo.tblPDdetails
WHERE (PONo = #PONumber)
GROUP BY id)as B On A.id = B.id
Inner Join tblpodetailshistory as C on A.id =C.id
where A.PONo = #PONumber)
END
I got this Error.
Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS.
Thank you in Advance.
You should include the column names and From keyword in the outer select statement
ALTER PROCEDURE [dbo].[POBalance] #PONumber nvarchar(50)
AS BEGIN
Select Description, POqty, PDQty, Balance, Unit, Unitprice, Partialflag from (
Select
A.Description,
C.qty as POqty,
B.QtyDelivered as PDQty,
case when A.partialflag ='false'
then '0'
else
A.qty end as Balance,
A.Unit,
A.Unitprice,
A.Partialflag
from tblPOdetails as A
Inner Join ( SELECT id, SUM(Qty) AS QtyDelivered
FROM dbo.tblPDdetails
WHERE (PONo = #PONumber)
GROUP BY id)as B On A.id = B.id
Inner Join tblpodetailshistory as C on A.id =C.id
where A.PONo = #PONumber)
END
Actually you don't need to write the outer select, it can be rewritten as
ALTER PROCEDURE [dbo].[POBalance] #PONumber nvarchar(50)
AS BEGIN
Select
A.Description,
C.qty as POqty,
B.QtyDelivered as PDQty,
case when A.partialflag ='false'
then '0'
else
A.qty end as Balance,
A.Unit,
A.Unitprice,
A.Partialflag
from tblPOdetails as A
Inner Join ( SELECT id, SUM(Qty) AS QtyDelivered
FROM dbo.tblPDdetails
WHERE (PONo = #PONumber)
GROUP BY id)as B On A.id = B.id
Inner Join tblpodetailshistory as C on A.id =C.id
where A.PONo = #PONumber
END
The issue is at the beginning of your query,
Select( Select ....
Remove the initial "Select (" and retry the query. When you run a
Select (Select ..)
the second select can only return one column (unless you concatenate the returned data).

Complex Full Outer Join

Sigh ... can anyone help? In the SQL query below, the results I get are incorrect. There are three (3) labor records in [LaborDetail]
Hours / Cost
2.75 / 50.88
2.00 / 74.00
1.25 / 34.69
There are two (2) material records in [WorkOrderInventory]
Material Cost
42.75
35.94
The issue is that the query incorrectly returns the following:
sFunction cntWO sumLaborHours sumLaborCost sumMaterialCost
ROBOT HARNESS 1 12 319.14 236.07
What am I doing wrong in the query that is causing the sums to be multiplied? The correct values are sumLaborHours = 6, sumLaborCost = 159.57, and sumMaterialCost = 78.69. Thank you for your help.
SELECT CASE WHEN COALESCE(work_orders.location, Work_Orders_Archived.location) IS NULL
THEN '' ELSE COALESCE(work_orders.location, Work_Orders_Archived.location) END AS sFunction,
(SELECT COUNT(*)
FROM work_orders
FULL OUTER JOIN Work_Orders_Archived
ON work_orders.order_number = Work_Orders_Archived.order_number
WHERE COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = '919630') AS cntWO,
SUM(Laborhours) AS sumLaborHours,
SUM(LaborCost) AS sumLaborCost,
SUM(MaterialCost*MaterialQuanity) AS sumMaterialCost
FROM work_orders
FULL OUTER JOIN Work_Orders_Archived
ON work_orders.order_number = Work_Orders_Archived.order_number
LEFT OUTER JOIN
(SELECT HoursWorked AS Laborhours, TotalDollars AS LaborCost, WorkOrderNo
FROM LaborDetail) AS LD
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = LD.WorkOrderNo
LEFT OUTER JOIN
(SELECT UnitCost AS MaterialCost, Qty AS MaterialQuanity, OrderNumber
FROM WorkOrderInventory) AS WOI
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = WOI.OrderNumber
WHERE COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = '919630'
GROUP BY CASE WHEN COALESCE(work_orders.location, Work_Orders_Archived.location) IS NULL
THEN '' ELSE COALESCE(work_orders.location, Work_Orders_Archived.location) END
ORDER BY sFunction
Try using the SUM function inside a derived table subquery when doing the full join to "WorkOrderInventory" like so...
select
...
sum(hrs) as sumlaborhrs,
sum(cost) as sumlaborcost,
-- calculate material cost in subquery
summaterialcost
from labordetail a
full outer join
(select ordernumber, sum(materialcost) as summaterialcost
from WorkOrderInventory
group by ordernumber
) b on a.workorderno = b.ordernumber
i created a simple sql fiddle to demonstrate this (i simplified your query for examples sake)
Looks to me that work_orders and work_orders_archived contains the same thing and you need both tables as if they were one table. So you could instead of joining create a UNION and use it as if it was one table:
select location as sfunction
from
(select location
from work_orders
union location
from work_orders_archived)
Then you use it to join the rest. What DBMS are you on? You could use WITH. But this does not exist on MYSQL.
with wo as
(select location as sfunction, order_number
from work_orders
union location, order_number
from work_orders_archived)
select sfunction,
count(*)
SUM(Laborhours) AS sumLaborHours,
SUM(LaborCost) AS sumLaborCost,
SUM(MaterialCost*MaterialQuanity) AS sumMaterialCost
from wo
LEFT OUTER JOIN
(SELECT HoursWorked AS Laborhours, TotalDollars AS LaborCost, WorkOrderNo
FROM LaborDetail) AS LD
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = LD.WorkOrderNo
LEFT OUTER JOIN
(SELECT UnitCost AS MaterialCost, Qty AS MaterialQuanity, OrderNumber
FROM WorkOrderInventory) AS WOI
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = WOI.OrderNumber
where wo.order_number = '919630'
group by sfunction
order by sfunction
The best guess is that the work orders appear more than once in one of the tables. Try these queries to check for duplicates in the two most obvious candidate tables:
select cnt, COUNT(*), MIN(order_number), MAX(order_number)
from (select order_number, COUNT(*) as cnt
from work_orders
group by order_number
) t
group by cnt
order by 1;
select cnt, COUNT(*), MIN(order_number), MAX(order_number)
from (select order_number, COUNT(*) as cnt
from work_orders_archived
group by order_number
) t
group by cnt
order by 1;
If either returns a row where cnt is not 1, then you have duplicates in the tables.

Grabbing Details of Customers who appear more than once

I'm getting a strange error with the below code. No column was specified for column 2 of 'no1'.
As far as I can tell it should work. I'm simply trying to get a collection of details about customers where the customers exist more than once on the receipts tbl.
SELECT
CM.ClientID,
CPN.Birthdate,
CM.ClientPassword
FROM
dbo.ClientMaster AS CM
JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
WHERE
CM.ClientID IN (
SELECT
no1.ClientID
FROM
(
SELECT
CM.ClientID,
COUNT(*)
FROM
dbo.ClientMaster AS CM
JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
WHERE
CP.PolicyNo IN (SELECT PolicyNo FROM Receipts)
AND CM.ClientID IS NOT NULL
AND Birthdate IS NOT NULL
AND ClientPassword IS NOT NULL
GROUP BY
CM.ClientID
HAVING
COUNT(*)>1
) AS no1
)
SOLUTION
Ah did not realise you don't need the Count(*) in the Select. Thanks guys!
This is what I ended up going with.
SELECT DISTINCT
CM.ClientID,
CPN.Birthdate,
CM.ClientPassword
FROM
dbo.ClientMaster AS CM
JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
WHERE
CM.ClientID IN (
SELECT
ClientID
FROM
Receipts
GROUP BY
ClientID
HAVING
COUNT(*)>1
)
AND CM.ClientID IS NOT NULL
AND Birthdate IS NOT NULL
AND ClientPassword IS NOT NULL
Your COUNT(*) column needs a name, like:
COUNT(*) AS RecordCount
You don't need to nest the same query twice for that. You can do this instead:
SELECT
CM.ClientID,
CPN.Birthdate,
CM.ClientPassword
FROM
dbo.ClientMaster AS CM
JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
GROUP BY CM.ClientID, CPN.Birthdate, CM.ClientPassword
HAVING COUNT(CM.ClientID) > 1