View query without sub selecting T-SQL - tsql

so I'm trying to build a view query but I keep failing using only joins so I ended up with this deformation.. Any tips on how I can write this query so I don't have to use 6 subselects?
The FeeSum and PaymentSum can be null, so ideally I do not want those in my result set and I also wouldn't like results where the FeeSum and the PaymentSum are equal.
Quick note: client is the table where the clients informations are stored (name, adress, etc..)
customer has a fk on client and is kind of a shell table for the client that store more information for the client,
payment is a list of all payments a customer did,
order is a list of all orders a customer did.
The goal is to get a list where we can track which customer has open fees to pay, based on the orders. It's a legacy project so don't ask why people can order before paying :)
SELECT
cu.Id as [CustomerId]
, CASE
WHEN cl.IsPerson = 1
THEN cl.[AdditionalName] + ' ' + cl.[Name]
ELSE cl.AdditionalName
END as [Name]
, cl.CustomerNumber
, (SELECT SUM(o.Fee) FROM [publication].[Order] o WHERE o.[State] = 2 AND o.CustomerId = cu.Id) as [FeeSum]
, (SELECT SUM(p.Amount) FROM [publication].[Payment] p WHERE p.CustomerId = cu.Id) as [PaymentSum]
, (SELECT MAX(o.OrderDate) FROM [publication].[Order] o WHERE o.[State] = 2 AND o.CustomerId = cu.Id) as [LastOrderDate]
, (SELECT MAX(p.PaymentDate) FROM [publication].[Payment] p WHERE p.CustomerId = cu.Id) as [LastPaymentDate]
, (SELECT MAX(f.Created) FROM [client].[File] f WHERE f.TemplateName = 'Reminder' AND f.ClientId = cl.Id) as [LastReminderDate]
, (SELECT MAX(f.Created) FROM [client].[File] f WHERE f.TemplateName = 'Warning' AND f.ClientId = cl.Id) as [LastWarningDate]
FROM
[publication].[Customer] cu
JOIN
[client].[Client] cl
ON cl.Id = cu.ClientId
WHERE
cu.[Type] = 0
Thanks in advance and I hope I didn't do anything wrong.
Kind regards

You could rewrite the correlated subqueries to instead use joins:
SELECT
cu.Id AS [CustomerId],
CASE WHEN cl.IsPerson = 1
THEN cl.[AdditionalName] + ' ' + cl.[Name]
ELSE cl.AdditionalName END AS [Name],
cl.CustomerNumber,
o.FeeSum,
p.PaymentSum,
o.LastOrderDate,
p.LastPaymentDate,
f.LastReminderDate,
f.LastWarningDate
FROM [publication].[Customer] cu
INNER JOIN [client].[Client] cl
ON cl.Id = cu.ClientId
INNER JOIN
(
SELECT CustomerId, SUM(Fee) AS [FeeSum], MAX(OrderDate) AS [LastOrderDate]
FROM [publication].[Order]
WHERE o.[State] = 2
GROUP BY CustomerId
) o
ON o.CustomerId = cu.Id
INNER JOIN
(
SELECT CustomerId, SUM(Amount) AS [PaymentSum], MAX(PaymentDate) AS [LastPaymentDate]
FROM [publication].[Payment]
WHERE o.[State] = 2
GROUP BY CustomerId
) p
ON p.CustomerId = cu.Id
INNER JOIN
(
SELECT ClientId,
MAX(CASE WHEN TemplateName = 'Reminder' THEN Created END) AS [LastReminderDate],
MAX(CASE WHEN TemplateName = 'Warning' THEN Created END) AS [LastWarningDate]
FROM [client].[File]
GROUP BY ClientId
) f
ON f.ClientId = cl.Id
WHERE
cu.[Type] = 0;

Related

Refine data elements using having clause tsql

I'm trying to pull a dataset that returns records ONLY when there are two QUALIFERs present. I've tried left joins, populating data in temp tables then manipulating something, then numerous having clauses (resulting in subquery selects, and additional groups). I would appreciate any assistance on what I can do further.
Query:
Select E, CASE WHEN QUALIFER = '1' THEN 'NAME1' WHEN QUALIFER = '2' then 'NAME2' ELSE 'FINALNAME' END AS TYPE, count(rt.ID) 'Number '
from TABLE_ONE co (nolock)
join TABLE_TWO rt (nolock)
on co.ID = rt.ID
where co.E in (select * from #tempEmail)
AND convert(date,co.INSERTED_TIMESTAMP)between '1/1/2020' and '8/15/2020'
AND TRANS_STATUS = 'APPROVED'
group by E, QUALIFER
order by E, QUALIFER
Current resultset:
E TYPE Number
FAKEEMAIL1#Gmail NAME1 1
FAKEEMAIL1#Gmail NAME2 1
otheremailj#gmail.com Name1 21
Desired resultset:
E TYPE Number
FAKEEMAIL1#Gmail NAME1 1
FAKEEMAIL1#Gmail NAME2 1
Thank you.
Let's try the below query. I used a temp table to make things more simple for my mind.
if object_id('tempdb.dbo.#email') is not null drop table #email
create table #email
(
email varchar(50),
typeValue varchar(15),
Number int
)
insert into #email(email, typeValue, Number)
Select
E,
CASE WHEN QUALIFER = '1' THEN 'NAME1' WHEN QUALIFER = '2' then 'NAME2' ELSE 'FINALNAME' END AS TYPE,
count(rt.ID) 'Number '
from TABLE_ONE co (nolock)
join TABLE_TWO rt (nolock)
on co.ID = rt.ID
where co.E in (select * from #tempEmail)
AND convert(date,co.INSERTED_TIMESTAMP)between '1/1/2020' and '8/15/2020'
AND TRANS_STATUS = 'APPROVED'
group by E, QUALIFER
select a.email, a.typeValue
from #email a
inner join
(
select email, typeValue, rank() over (partition by email order by typeValue) as typeCount
from #email t
) as b
on b.email = a.email
and b.typeCount > 1

Grades of each quiz in Moodle

I'm trying to get grades of each question, I have a query but it only return final grade of whole exam, but i want grade of each question, how to get it?
Here is query that i have:
SELECT mdl_grade_items.id AS ItemID,
mdl_course.shortname AS CourseShortname,
mdl_grade_items.itemname AS ItemName,
mdl_grade_items.grademax AS ItemGradeMax,
mdl_grade_items.aggregationcoef AS ItemAggregation,
mdl_grade_grades.finalgrade AS FinalGrade,
mdl_user.username AS StudentID,
mdl_user.id
FROM mdl_grade_items
INNER JOIN mdl_grade_grades
ON mdl_grade_items.id = mdl_grade_grades.itemid
INNER JOIN mdl_role_assignments
ON mdl_grade_grades.userid = mdl_role_assignments.userid
AND mdl_grade_items.courseid = mdl_role_assignments.mdlcourseid
INNER JOIN mdl_course
ON mdl_course.id = mdl_grade_items.courseid
INNER JOIN mdl_user
ON mdl_user.id = mdl_role_assignments.userid
Ok, i found it
SELECT mqa.id,meqi.grade * (select fraction from mdl_question_attempt_steps where
questionattemptid = mqas.questionattemptid and state like 'mangr%' order by id desc limit
1 ) finalgrade,me.course , mqas.userid,u.firstname, u.lastname, mqa.questionsummary,
mqa.responsesummary , meqi.grade
FROM mdl_question_attempts mqa
left JOIN mdl_question_attempt_steps mqas ON mqa.id = mqas.questionattemptid
left JOIN mdl_user u ON mqas.userid = u.id
left JOIN mdl_examm_question_instances meqi ON meqi.question = mqa.questionid
left JOIN mdl_examm me ON meqi.examm = me.id
WHERE me.course= $courseID and userid = $userID

Join two queries become one subquery

I want to ask how to combine these two queries become one subquery?
select c.CustomerName, A.Qty
from Customer c join (select s.CustomerID, pd.Date, s.Qty
from Period pd join Sales s on pd.TimeID = s.TimeID) A on c.CustomerID = A.CustomerID
where #Date = A.Date
and
select sum(case when (pd.Date between '2010-03-15' and #Date) then s.Qty else 0 end) as TotalQty
from Period pd full join Sales s on pd.TimeID = s.TimeID full join Customer c on s.CustomerID = c.CustomerID
group by c.CustomerName, c.CustomerID
They should result one table contains these following columns: CustomerName, Qty, and TotalQty. I've tried many ways but they didn't work at all. Really hope your help, thanks.
Answering your question assuming you are looking at the result as one row and not "column" :
select c.CustomerName, A.Qty,(select sum(case when (pd.Date between '2010-03-15' and #Date) then s.Qty else 0 end)
from Period pd full join Sales s on pd.TimeID = s.TimeID full join Customer c on s.CustomerID = c.CustomerID
group by c.CustomerName, c.CustomerID
) as TotalQty
from Customer c join (select s.CustomerID, pd.Date, s.Qty
from Period pd join Sales s on pd.TimeID = s.TimeID) A on c.CustomerID = A.CustomerID
where #Date = A.Date
If you still want the result as a single column , google "row to column transpose"

The multi-part identifier "..." could not be bound

I get error (The multi-part identifier "f.FormID" could not be bound.) running this query:
select f.FormID, f.Title, fv.UserName
from Forms f join (
SELECT FormID
FROM Reports
WHERE (ReportID = #ReportID)
UNION
SELECT FormRelations.ForigenFormID
FROM FormRelations INNER JOIN
Forms ON FormRelations.ForigenFormID = Forms.FormID
WHERE (FormRelations.PrimaryFormID =
(SELECT FormID
FROM Reports
WHERE (ReportID = #ReportID)))
) ids
on f.FormID = ids.FormID
LEFT OUTER JOIN (select top 1 UserName, FormID from FormValues where FormID = f.FormID and UserName = #UserName) fv
ON f.FormID = fv.FormID
Please someone help me :(
#bluefeet:
I want such a result:
01304636-FABE-4A3E-9487-A14B012F9A61 item_1 1234567890
C0455E97-788A-4305-876A-A15000CFE928 item_2 1234567890
7719F37E-7021-4ABD-91ED-A15301830324 item_3 1234567890
If you need to use your alias inside of your subquery like that, you might want to look at using the APPLY operator:
select f.FormID, f.Title, fv.UserName
from Forms f
join
(
SELECT FormID
FROM Reports
WHERE (ReportID = #ReportID)
UNION
SELECT FormRelations.ForigenFormID
FROM FormRelations
INNER JOIN Forms
ON FormRelations.ForigenFormID = Forms.FormID
WHERE (FormRelations.PrimaryFormID = (SELECT FormID
FROM Reports
WHERE (ReportID = #ReportID)))
) ids
on f.FormID = ids.FormID
CROSS APPLY
(
select top 1 UserName, FormID
from FormValues
where FormID = f.FormID
and UserName = #UserName
) fv
Or you can use row_number():
select f.FormID, f.Title, fv.UserName
from Forms f
join
(
SELECT FormID
FROM Reports
WHERE (ReportID = #ReportID)
UNION
SELECT FormRelations.ForigenFormID
FROM FormRelations
INNER JOIN Forms
ON FormRelations.ForigenFormID = Forms.FormID
WHERE (FormRelations.PrimaryFormID = (SELECT FormID
FROM Reports
WHERE (ReportID = #ReportID)))
) ids
on f.FormID = ids.FormID
LEFT JOIN
(
select UserName, FormID,
ROW_NUMBER() over(PARTITION by FormID, UserName order by FormID) rn
from FormValues
where UserName = #UserName
) fv
on f.FormID = fv.FormID
and fv.rn = 1

T-SQL Nested Subquery

I want to place this working code within a SQL Statement, OR do I need to perform a UDF.
The result set is a one line concatenation, and I want it to be place in every one of the overall result set lines.
----
MAIN QUERY
SELECT
H.CONNECTION_ID,
H.SEQUENTIAL_NO,
H.INVOICE_NUMBER,
H.INVOICE_DATE,
H.LAST_INVOICE_NUMBER,
H.LAST_INVOICE_DATE,
CAST(CASE
WHEN H.COLLECT_DEPOSIT = 1 THEN '-'
ELSE CAST(H.PAYMENT_DUE_DATE AS NVARCHAR(20))
END AS SMALLDATETIME) AS PAYMENT_DUE,
H.JOB_NUMBER,
H.CUST_JOB_NUMBER,
HDR.SALES_PERSON,
H.INSIDE_SALES_PERSON,
H.IS_LAST_INVOICE,
CASE
WHEN H.COLLECT_DEPOSIT = 1 THEN 'CASH'
ELSE H.PAYMENT_TERMS_DESCRIPTION
END AS PAYMENT_TERMS,
H.PRINTED,
H.NOTES,
CUR.ID,
CUR.CODE,
CASE CUR.CODE
WHEN 'USD' THEN '001-106624-211'
WHEN 'EUR' THEN '001-106624-101'
WHEN 'GBP' THEN '001-106624-100'
ELSE '001-106624-001'
END AS BANK_ACCT,
CUR.EXCHANGE_RATE,
H.BILL_CONTACT,
H.CUST_ACCOUNT,
H.CUST_NAME,
H.CUST_ADDR1,
H.CUST_ADDR2,
H.CUST_CITY,
H.CUST_STATE,
H.CUST_ZIP,
H.CONTACT_PHONE_NUMBER,
H.CONTACT_PHONE_NUMBER2,
H.ORDERED_BY_CONTACT,
H.SHIP_TO_NAME,
H.SHIP_TO_ADDR1,
H.SHIP_TO_ADDR2,
H.SHIP_TO_CITY,
H.SHIP_TO_STATE,
H.SHIP_TO_ZIP,
H.SITE_PHONE_NUMBER,
H.SITE_PHONE_NUMBER2,
H.OFFICE_NAME,
H.OFFICE_ADDR1,
H.OFFICE_ADDR2,
H.OFFICE_CITY,
H.OFFICE_STATE,
H.OFFICE_ZIP,
H.OFFICE_PHONE_NUMBER,
H.OFFICE_FAX_NUMBER,
H.DELIVERY_TICKET_NUMBER,
H.PO_NUMBER,
H.DUMMY_INVOICE_TEXT,
(SELECT MESSAGE FROM REPORT_MESSAGES WHERE CODE = 'INVOICE') ADVERT_MESSAGE,
(SELECT MAX(DISCOUNT_PERCENTAGE) FROM PRTINVITEM I2 WHERE I2.CONNECTION_ID = H.CONNECTION_ID AND I2.INVOICE_NUMBER = H.INVOICE_NUMBER) AS MAX_DISCOUNT,
I.ITEM,
I.DESCRIPTION,
I.QUANTITY,
I.UNIT_OF_MEASURE,
I.MINIMUM_CHARGE,
I.WEEKLY_CHARGE,
I.MONTHLY_CHARGE,
I.START_OF_BILLING_PERIOD,
I.END_OF_BILLING_PERIOD,
I.DAYS_USED,
I.WEEKS_USED,
I.DISCOUNT_PERCENTAGE,
I.TAX_CODE_FOR_ITEM,
I.INVENTORY_TYPE,
I.BILLING_LOGIC_TYPE,
I.ACTUAL_WEEKLY_CHARGE_USED,
I.DAYS_IN_ACTUAL_WEEKLY_CHARGE,
II.CHARGEABLE_DAYS,
II.CHARGEABLE_WEEKS,
II.CHARGEABLE_MONTHS,
II.FREE_DAYS_THIS_INVOICE,
CNV.TOTAL_NET_VALUE,
CNV.TOTAL_TAX_VALUE,
CNV.TOTAL_GROSS_VALUE,
CNV.TOTAL_GROSS_VALUE_NS,
CNV.NET_LINE_VALUE,
CMP.EMAIL_ADDRESS
FROM (PRTINVHDR H INNER JOIN PRTINVITEM I ON H.CONNECTION_ID = I.CONNECTION_ID AND H.INVOICE_NUMBER = I.INVOICE_NUMBER)
INNER JOIN INVOICEHDR HDR ON I.INVOICE_NUMBER = HDR.INVNO
INNER JOIN CUSTOMERS CST ON H.CUST_ACCOUNT = CST.CUSTNUM
INNER JOIN JOB JOB ON H.JOB_NUMBER = JOB.JOBNUM
INNER JOIN CURRENCY CUR ON HDR.CURRENCY_ID = CUR.ID
INNER JOIN VWCURRENCYCONVERSION CNV ON I.CONNECTION_ID = CNV.CONNECTION_ID AND I.INVC_UCOUNTER = CNV.INVC_UCOUNTER
INNER JOIN COMPANY CMP ON H.OFFICE_CODE = CMP.OFFICE
INNER JOIN INVOICEITEM II ON I.INVOICE_NUMBER = II.INVNO AND I.INVC_UCOUNTER = II.INVC_UCOUNTER
ORDER BY
H.SEQUENTIAL_NO,
I.PRINT_SEQUENCE
ASC
----
COALESCE QUERY
DECLARE
#DTICKET NVARCHAR(20),
#PUMPCATEGORYNAME NVARCHAR(3999)
SET #DTICKET = ''
SET #PUMPCATEGORYNAME = NULL
(SELECT
#DTICKET = DTICKET,
#PUMPCATEGORYNAME = COALESCE(#PUMPCATEGORYNAME + ', ', '' ) + PUMPCATEGORYNAME
FROM (SELECT
BHDR.DTICKET,
SCD.PUMPCATEGORYNAME
FROM PRTTICKHDR PHDR
INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET
INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER
LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY
WHERE SCD.PUMPCATEGORYNAME IS NOT NULL)
SUBCATEGORYDESCRIPTION)
SELECT #DTICKET, #PUMPCATEGORYNAME
Not really sure what you are asking for but you can doing something along the lines of
Select col1 + ', ' + col2 + ', ' + col3 etc....