I have two tables in SQL and I want to first join them and then use a pivot and get sum for each column by date.
For example:
Table Name Sales:
I have another Table called Manufacturer:
I want to join these tables and sum up the totals for Offer_Price, Sale_Price and Discount. I want to get the results date wise for each Manufacturer.
I wrote a query:
*/
Select Manufacturer_Name ,
date,
Offer_Price,
Sale_Price,
Discount
From
(
Select M.name, S.Date, S.Offer_Price, S.Sale_Price , S.Discount
from dbo.sales S
Inner join dbo.Manufacturer M on S.m_id = M.M_id
) as PivotData
Pivot (Sum(Offer_Price) , sum (Sale_Price), sum (Discount)
For date in ([2020-03-22], [2020-03-21], [2020-03-20])) as pivoting /*
But I get an error:
Incorrect syntax near ','.
This error is for the row where I am adding up the columns.
I am trying to learn pivot but I am stuck here. Can someone help?
Please note that I made up the data above, these are not the actual columns and tables but they are similar.
The results I want are like:
For Manufacturer Vivo and date 03/22/2020 it should add up and show offer price as 20,000, sale_Price as 19900, discount as 100 in a single row.
Related
I run into a problem. I have three tables: product, where is stored his price and name. Then table Query with atributtes like description of searched words and their frequency(so there are no duplicates). And table UsersQuery, where each of the searched words of the user are stored.
PRODUCT
id
price
name
QUERY
id
description_query
number_of_freq
USERSQUERY
id
query_id FK
user_id FK
timestamp
I have to calculate for each month in a given year and subsequent years (January 2018, February 2018,…), calculate the ratio between those search queries that contain the product name and those that do not. If the given ratio is not defined for the given month, the output should be NULL.
Do you guys know how it would be possible?
So far I just have this
select q.description_query,
to_char(uq.timestamp, 'YYYY-MM') as year_month
from usersquery as uq
join query as q ON q.id = uq.query_id;
But I dont really know how to bind table with products, just with his atributte name. Should I use some sort of fulltext search using tsvector?
-- table is case insensitive so use product,query, user_query. please refer manual 4.1 lexical structure.
demo
I hope I understand correctly. The number_of_freq refer to the time the query contain the product name. and if number_of_freqtext = 0 means that this query don't contain the product key word.
basically a generate_series to generate date series data(later for left or right join), count filter function to count the freq is 0.
final code:
WITH cte AS (
SELECT
to_char(querytimestamp, 'YYYY-MM') AS tochar1,
count(number_of_freq) AS count_all,
count(number_of_freq) FILTER (WHERE number_of_freq = 0) AS count_0
FROM
query
JOIN user_query uq ON query.query_id = uq.query_id
WHERE
querytimestamp >= '2021-01-01 00:00' at time zone 'UTC'
AND querytimestamp <= '2022-12-31 23:59' at time zone 'UTC'
GROUP BY
1
),
cte2 (
yearmonth
) AS (
SELECT
to_char(g, 'YYYY-MM')
FROM
generate_series('2021-01-01', '2022-12-31', interval '1 month') g
)
SELECT
yearmonth,
cte.*,
round(cte.count_0::numeric / count_all, 2)
FROM
cte
RIGHT JOIN cte2 ON cte.tochar1 = yearmonth;
updated demo
About count the frequency of the word. full text search won't help.
Since full text search will parse 'product.id' as 'product.id'.
You may need regexp split string functions.
refer count frequency demo to solve the words count frequency issue:
enter image description here> Write a select statement that returns InvoiceNumber, VendorName and InvoiceDate
from the Vendors and Invoices table. Use the following correlations for each table:
Vendors v
Invoices i
Filter the results to return only rows where a balance is due
I should be getting back 11 rows but I am getting 114 rows.
Select InvoiceNumber, VendorName, InvoiceDate
From Vendors as v
join Invoices as i on v.VendorId = i.VendorID
where InvoiceTotal > 0
Query above looks good.
If you got unexpected number of rows in result it means (like #Dale-K mentioned in comment) wrong condition. InvoiceTotal does not look like amount left to pay.
Look for column like InvoiceDue or InvoiceBalance.
Or there is also column with due date and this should be added to condition (to find overdued invoices).
Or there is another table keeping payments which should be joined too.
Without structure of tables and sample data we can only guess.
However this looks like homework, so look for the column with current balance of invoice and use it.
I have an Access database with customer IDs. Each customer can have multiple orders and each order can be of a different type. I have three separate tables (Online, In-store, Payment Plan) for each order type with various amounts from each order, all are related to a customer ID. In one of the tables, there are two types of order types that amounts must be maintained separately withing the same table. I want to sum each order type in another table called Totals. I can successfully create a query to get the sums for each type based on the customer ID but I am not sure how to pull those values in my Totals table. The scenario below is repeated for multiple customers and each type is its own table---the payment plans are in a table together. I have historical data so I am limited to how I can manipulate as far as merging fields and what not.
Customer ID#: 1
Order Type: Online
Online Amount: $20.00
Order Type: Online
Online Amount: $40.00
Sum of Online Amount: $60.00
Order Type: In-store
Online Amount: $35.00
Order Type: In-store
Online Amount: $60.00
Sum of In-Store Amount: $95.00
Order Type: Payment Plan
Payment Plan 1 Amount: $30.00
Payment Plan 1 Amount: $23.00
Sum of Payment Plan 1 Amount: $53.00
Order Type: Payment Plan 2
Payment Plan 2 Amount: $35.00
Payment Plan 2 Amount: $30.00
Sum of Payment Plan 2 Amount: $65.00
In my Totals table I have a field for each type that sums the amount spent by each customer ID and then a field where all of their order types are summed into one overall total field.
I am learning as I go so any help/example is appreciated. Thank you.
Having separate tables for your different order types doesn't help. For a database it would be better to have a single table for all sales with a sale_type field.
You don't describe exactly what your tables look like, so I've had to make a couple of assumptions. If your tables contain an OrderType field then you can create a Union query to join all your sales together:
SELECT CustomerID
, OrderType
, Amount
FROM Online
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [In-Store]
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [Payment Plan]
If you don't have an OrderType you can hard-code the values into the query:
SELECT CustomerID
, "Online" AS OrderType
, Amount
FROM Online
UNION ALL SELECT CustomerID
, "In-Store"
, Amount
FROM [In-Store]
UNION ALL SELECT CustomerID
, "Payment Plan"
, Amount
FROM [Payment Plan]
Note - The field name is declared for the OrderType in the first Select block. You could do it in each block, but Access only looks at the first.
Like all queries, the results come in table form and can be treated as such. So now we need to list the CustomerName (I'm assuming you have a Customers table), the OrderType and the sum of the amount for that Customer & OrderType.
SELECT CustomerName
, OrderType
, SUM(Amount)
FROM Customers INNER JOIN
(
SELECT CustomerID
, OrderType
, Amount
FROM Online
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [In-Store]
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [Payment Plan]
) T1 ON Customers.CustomerID = T1.CustomerID
GROUP BY CustomerName
, OrderType
All sales in your three tables will have a customer within the customers table so we can use an INNER JOIN to return only records where the value appears in both tables (Customers table & result of query table).
The UNION QUERY is wrapped in brackets and given the name T1and joined to the Customers table on the CustomerID field.
We group all fields that aren't part of an aggregate function, so group on CustomerName and OrderType and sum the Amount field.
This is all you really need to do - let the query run each time you want the totals to get the most up to date values. There's shouldn't be a need to push the results to a Totals table as that will be out of date as soon as you make a new sale (or someone returns something).
If you really want to INSERT these figures into a Total table just add a first line to the SQL:
INSERT INTO Total (CustomerName, OrderType, Amount)
Here is a dirty workaround, though I think there might be a more direct solution to it.
You could create an output table (I broke it down to ID, Online, InStore and Total) and use DSum functions within an UPDATE query.
UPDATE tbl_Totals SET
Total_InStore = DSum("Amount", "tbl_InStore", "Customer_ID = " & Customer_ID),
Total_Online = DSum("Amount", "tbl_Online", "Customer_ID = " & Customer_ID),
Total = DSum("Amount", "tbl_InStore", "Customer_ID = " & Customer_ID) + DSum("Amount", "tbl_Online", "Customer_ID = " & Customer_ID)
I've two tables
income
expense
the problem is I want to query all the data from both tables
SELECT income.date AS IN_DATE, expense.date AS EX_DATE FROM income, expense
I get weird result data is double times from db as you can see
you can try this out HERE
how can I get distinct results not double and at last wanna ask don't have idea of getting data from both tables and sort by date descending.
My guess is that you want union all:
select 'income' as which, id, title, date
from income
union all
select 'expense' as which, id, title, date
from expense;
This will give you a result set containing the rows from the two tables, with an identifier of which table each row comes from.
You can order by date and do other manipulations if you use a subquery:
select ie.*
from (select 'income' as which, id, title, date
from income
union all
select 'expense' as which, id, title, date
from expense
) ie
order by date desc;
Your simple SELECT does a cross product with the two columns (IN_DATE, EX_DATE). Hence, you get every possible combination of the values from both columns. INNER JOIN income ON expense.id=income.id or WHERE income.id == expense.id should do the trick.
You need to match the same ids, else SQL will just output any possible combination.
SELECT income.date AS IN_DATE, expense.date AS EX_DATE FROM income, expense WHERE income.id LIKE expense.id
I am facing 1 prob in implementing business solution. Any help would be much appreciated.
There is 1 table with 3 columns.
Table Employee
(
Id, Name, Salary
)
Values -
(1,John,10000),
(2,Rey, 15000),
(3,John,20000)
Expected Output -
It should fetch only distinct employees and for duplicate records of employee, it should fetch sum of salary.
So, output should be like this -
(1,john,30000),
(2,Rey,15000)
Please help
Check the basic sintaxis for GROUP BY
SELECT MIN(ID), Name, SUM(Salary)
FROM Employee
GROUP BY Name
The interesting part here is aggregation functions doesnt need to be at the end. As are usually show in the examples