I'm working with SQL Server 2008
I have 2 tables and I want to get 2 columns from the 1st table and 1 column from the 2nd table
when I make JOIN it gives me another things...
here is my code:
Select SUM(Sales.CDnum) as CDnum, SUM(Sales.Total) as TotalMoney,
SUM(Expenses.Costs) as Expenses, SUM(Sales.Total - Expenses.Costs) as Winnings
from Sales
JOIN Expenses
ON Sales.ID = Expenses.ID
but when I execute the code it gives me only one raw from the 1st table and 1 raw from the second ... because I have 1 raw in the 2nd table and 1st I have many raws...
someone can help me....
as I see ID columns are not related to each other in both tables, so you need to union them, for example like in this query:
select sum(q.sales), sum(q.expense), sum(q.sales)-sum(q.expense) as winnings
from (
select sum(Sales.Total) as sales, 0 as expense from Sales
union all
select 0 as sales, sum(Expenses.Costs) as expense from Expenses
) as q
Related
So I've got a small DB that has like subsections that come under a single section. Unfortunately, the DB doesn't have a "section" column and just the subsections and they have a "Inventory" column that has either "Computer" or "Laptop" in it. I've made a query that at the very least provides me with the total count of each of these "Inventory" column against each subsection.
However, I'm trying to combine the subsections into a single row and the total count of those subsections alongside it as well. Example of what I'm trying to say:
subsections
inventory
a_subsec1
comp
a_subsec1
comp
a_subsec2
lap
a_subsec2
comp
a_subsec3
lap
a_subsec3
comp
What I'm currently getting:
d_sub
inv_count_comp
a_subsec1
2
a_subsec2
1
a_subsec3
1
What I WANT to get:
D_SUB
total_comp_count
a_sec
4
Here's the query that I'm currently running to get that second table:
SELECT DISTINCT "subsections", COUNT("inventory") FROM mytable WHERE "inventory" = 'comp' GROUP BY "subsections" ORDER BY "subsections" ASC
Thank you.
substring the column then you can treat all the row as same subsection.
with tb as(
select 'a_subsec1' sec,'comp' inv
union all
select 'a_subsec1' sec,'comp' inv
union all
select 'a_subsec2' sec,'lap' inv
union all
select 'a_subsec2' sec,'comp' inv
union all
select 'a_subsec3' sec,'lap' inv
union all
select 'a_subsec3' sec,'comp' inv
)
select msec,sum(inv_comp) total from(
select concat(substr(sec,1,1),'_sec') as msec,
case when inv='comp' then 1 else 0 end as inv_comp,
tb.*
from tb) z
group by msec
this query might not be the one you want without some modify but main idea is same.
db<>fiddle
I'm trying to query an inventory database to show me how much wax is remaining on hand. Currently this is how I have the query set up:
SELECT * FROM (
SELECT SUM(OC.Quantity) AS oz_Wax_Ordered
FROM Order_In AS OC
WHERE (OC.Component) like ('Wax')
GROUP BY OC.Component
UNION SELECT SUM(C.Wax_Used) AS oz_Wax_Used
FROM Fragrance_Oils AS FO INNER JOIN Candles AS C ON FO.FragranceID = C.Fragrance
GROUP BY FO.Component
);
This shows me a single column with the second SELECT statement totaling the wax used, and the third SELECT totaling the wax ordered, displayed in rows 1 and 2, respectively.
I'm trying to have the total wax used subtract from the total wax ordered. I can share more information about the database itself if needed. Thanks!
You could sum the values:
SELECT
SUM([oz_Wax]) AS oz_Wax_OnHand
FROM
(SELECT SUM(OC.Quantity) AS oz_Wax
FROM Order_In AS OC
WHERE (OC.Component) like ('Wax')
GROUP BY OC.Component
UNION ALL
SELECT -SUM(C.Wax_Used)
FROM Fragrance_Oils AS FO
INNER JOIN Candles AS C
ON FO.FragranceID = C.Fragrance
GROUP BY FO.Component);
I´m having issues with the following query. I have two tables; Table Orderheader and table Bought. The first query I execute gives me, for example, two dates. Based on these two dates, I need to find Production data AND, based on the production data, I need to find the Bought data, and combine those data together. Lets say I do the following:
Select Lotdate From Orderheader where orhsysid = 1
This results in two rows: '2019-02-05' and '2019-02-04'. Now I need to do two things: I need two run two queries using this result set. The first one is easy; use the dates returned and get a sum of column A like this:
Select date, SUM(Amount) from Orderheader where date = Sales.date() [use the two dates here]
The second one is slighty more complicated, I need to find the last day where something has been bought based on the two dates. Production is everyday so Productiondate=Sales.date()-1. But Bought is derived from Productionday and is not everyday so for every Productionday it needs to find the last Boughtday. So I can't say where date = Orderheader.date. I need to do something like:
Select date, SUM(Amount)
FROM Bought
WHERE date = (
SELECT top 1 date
FROM Bought
WHERE date < Orderheader.date)
But twice, for both the dates I got.
This needs to result in 1 table giving me:
Bought.date, Bought.SUM(AMOUNT), Orderheader.date, Orderheader.SUM(AMOUNT)
All based on the, possible multiple, Lotdate(s) I got from the first query from Sales table.
I've been struggling with this for a moment now, using joins and nested queries but I can't seem to figure it out!
Example sample:
SELECT CONVERT(date,ORF.orfDate) as Productiedatum, SUM(orlQuantityRegistered) as 'Aantal'
FROM OrderHeader ORH
LEFT JOIN OrderFrame ORF ON ORH.orhFrameSysID = ORF.orfSysID
LEFT JOIN OrderLine ORL ON ORL.orhSysID = ORH.orhSysID
LEFT JOIN Item ON Item.itmSysID = ORL.orlitmSysID
where CONVERT(date,ORF.orfDate) IN
(
SELECT DISTINCT(CONVERT(date, Lot.lotproductiondate)) as Productiedatum
FROM OrderHeader ORH
LEFT JOIN Registration reg ON reg.regorhSysID = ORH.orhSysID
LEFT JOIN StockRegistration stcreg ON stcreg.stcregRegistrationSysID = reg.regSysID
LEFT JOIN Lot ON Lot.lotSysID = stcregSrclotSysID
WHERE ORH.orhSysID = 514955
AND regRevokeRegSysID IS NULL
AND stcregSrcitmSysID = 5103
)
AND ORL.orlitmSysID = 5103
AND orldirSysID = 2
AND NOT orlQuantityRegistered IS NULL
GROUP BY Orf.orfDate
Sample output:
Productiedatum Aantal
2019-02-05 20
2019-02-06 20
Here I used a nested subquery to get the results from 'Production' (orderheader) because I just can use date = date. I'm struggling with the Sales part where I need to find the last date(s) and use those dates in the Sales table to get the sum of that date.
Expected output:
Productiedatum Aantal Boughtdate Aantal
2019-02-04 20 2019-02-01 55
2019-02-05 20 2019-02-04 60
Try this.
IF OBJECT_ID('tempdb..#Production') IS NOT NULL DROP TABLE #Production
IF OBJECT_ID('tempdb..#Bought') IS NOT NULL DROP TABLE #Bought
CREATE table #Production(R_NO int,ProductionDate datetime,ProductionAmount float)
CREATE table #Bought(R_NO int,Boughtdate datetime,Boughtamount float)
insert into #Production(ProductionDate,ProductionAmount,R_NO)
select p.date ProductionDate,sum(Amount) ProductionAmount,row_number()over (order by p.date) R_NO
from Production P
join Sales s on p.date=S.date-1
where orhsysid=1
group by p.date
declare #loop int,#ProdDate datetime
select #loop =max(R_NO) from #Production
while (1<=#loop)
begin
select #ProdDate=ProductionDate from #Production where r_no=#loop
insert into #Bought(Boughtdate,Boughtamount,R_NO)
select Date,Sum(Amount),#loop R_NO from Bought where date=(
select max(date) from bought B
where B.Date<#ProdDate)
group by Date
set #loop=#loop-1
end
select ProductionDate,ProductionAmount,Boughtdate,Boughtamount from #Bought B
join #Production p on B.R_NO=P.R_NO
Need help with active record query, I have customers table with name and balance fields.
How can I make query that will return 6 values, first 5 is top customers by balance and 6th one is sum of all others?
need to select name and balance, for others it will custom name ''Other
Divide et impera: make two view then put results together
select *
from ( select * from view_top_5
union
select * from view_sum )
where view_top_5 is view (or a subquery) that gives you the top 5 customers, view_sum is a query giving you the sum. To get "all others" you can build your query from this skeleton:
-- skeleton for view "view_sum"
select <what you need>
from mytable
where customer_id not in (select client_id
from view_top_5)
I have 2 Tables in Ms Access
tbl_Master_Employess
tbl_Emp_Salary
I want to show all the employees in the employee table linked with employee salary table
to link both table the id is coluqEmpID in both table
In the second table, I have a date column. I need a query which should fetch records from both tables using a particular date
I tried the following query:
select coluqEID as EmployeeID , colEName as EmployeeName,"" as Type, "" as Amt
from tbl_Master_Employee
union Select b.coluqEID as EmployeeID, b.colEName as EmployeeName, colType as Type, colAmount as Amt
from tbl_Emp_Salary a, tbl_Master_Employee b
where a.coluqEID = b.coluqEID and a.colDate = #12/09/2013#
However, it shows duplicates.
Query4
EmployeeID EmployeeName Type Amt
1 LAKSHMANAN
1 LAKSHMANAN Advance 100
2 PONRAJ
2 PONRAJ Advance 200
3 VIJAYAN
4 THIRUPATHI
5 VIJAYAKUMAR
6 GOVINDAN
7 TAMILMANI
8 SELVAM
9 ANAMALAI
10 KUMARAN
How would I rewrite my query to avoid duplicates, or what would be a different way to not show duplicates?
The problem with your query is that you are using union when what you want is a join. The union is first going to list all employees with the first part:
select coluqEID as EmployeeID , colEName as EmployeeName,"" as Type, "" as Amt
from tbl_Master_Employee
and then adds to that list all employee records where they have a salary with a certain date.
Select b.coluqEID as EmployeeID, b.colEName as EmployeeName, colType as Type,
colAmount as Amt
from tbl_Emp_Salary a, tbl_Master_Employee b
where a.coluqEID = b.coluqEID and a.colDate = #12/09/2013#
Is your goal to get a list of all employees and only display salary information for those who have a certain date? Some sample data would be useful. Assuming the data here: SQL Fiddle this query should create what you want.
Select a.coluqEID as EmployeeID, colEName as EmployeeName,
b.colType as Type, b.colAmount as Amt
FROM tbl_Master_Employees as a
LEFT JOIN (select coluqEID, colType, colAmount FROM tbl_EMP_Salary
where colDate = '20130912') as b ON a.coluqEID = b.coluqEID;
The first step is to create a select that will get you just the salaries that you want by date. You can then perform a join on this as if you were performing a separate query. You use a LEFT JOIN because you want all of the records from one side, the employees, and only the records that match your criteria from the second side, your salaries.
I believe you will need a join, however as to your question on Unique names.
select **DISTINCT** coluqEID as EmployeeID
Adding the distinct operator would give only uniquely returned results.