How to output results of multiple queries together? - sql

I want to display result of 3 selects together in one window, in the same time.
First:
SELECT sum(r.punkty)
,r.id_kierowcy
FROM wyniki AS r
INNER JOIN wyscigi AS w ON r.id_wyscigu = w.id_wyscigu
WHERE w.rok = 2006
GROUP BY r.id_kierowcy
ORDER BY sum(r.punkty) DESC limit 1
Second:
SELECT sum(r.punkty)
,r.id_kierowcy
FROM wyniki AS r
INNER JOIN wyscigi AS w ON r.id_wyscigu = w.id_wyscigu
WHERE w.rok = 2000
GROUP BY r.id_kierowcy
ORDER BY sum(r.punkty) DESC limit 1
Third:
SELECT sum(r.punkty)
,r.id_kierowcy
FROM wyniki AS r
INNER JOIN wyscigi AS w ON r.id_wyscigu = w.id_wyscigu
WHERE w.rok = 2012
GROUP BY r.id_kierowcy
ORDER BY sum(r.punkty) DESC limit 1
In brief there is one difference in the selects, that is WHERE [2000, 2006, 2012]
Is the way to connect these selects? I must display them as one result set
EDIT: I will try to explain my exercise.
I have 2 tables:
Results and races.
Results contains 3 columns:
id_driver
/points
/id_race
Races contains 3 columns:
id_race
/year
/place
Races are between 2000 and 2012 years
I need to do classification of races in the 2000, 2006, 2012 and establish which one driver(id_driver) won each year. So I'm trying to do like that
SELECT sum(r.points)
,r.id_driver
FROM results AS r
INNER JOIN races AS x ON r.id_race = x.id_race
WHERE x.year = 2012
GROUP BY r.id_driver
ORDER BY sum(r.points) DESC limit 1
and the same for 2006 and 2000, but i need to display that as one result set, that is my problem I dont know how to connect it.

Related

SQL Queries Returning Non-equivalent Results and Different Counts Every Run

So I have 2 SQL queries both including the same variable: basically (n_orders and orders_count) should return the same exact results. Problem is:
the 2 columns are not always equivalent for all values
the count of different values changes every run
so first run could be that 20 rows have different (n_orders, orders_count) values then 2nd run says count of different values is 56 for example and so on with changing counts every run.
Query 1:
SELECT product_id,
packing_unit_id,
count(DISTINCT product_sales_order.sales_order_id)
FROM product_sales_order
WHERE product_sales_order.created_at::date BETWEEN '{start}' AND '{end}'
GROUP BY 1, 2
ORDER BY product_id, packing_unit_id
Query 2:
select kpis.*, lr.lr
FROM
(SELECT product_sales_order.product_id,
product_sales_order.packing_unit_id,
count(DISTINCT product_sales_order.sales_order_id) AS orders_count,
count(DISTINCT sales_orders.retailer_id) AS retailers_count,
count(DISTINCT product_sales_order.sales_order_id)*1.0 / count(DISTINCT sales_orders.retailer_id) AS frequency,
(count(DISTINCT sales_orders.retailer_id)*1.0 /(SELECT count(DISTINCT sales_orders.retailer_id) AS month_retailers
FROM sales_orders
JOIN retailers on retailers.id = sales_orders.retailer_id
WHERE sales_orders.created_at::Date BETWEEN '{start}' AND '{end}'
AND sales_orders.sales_order_status_id = 6
AND retailers.is_market_type_private = false)) AS reach,
sum(product_sales_order.total_price) AS nmv,
(sum(product_sales_order.total_price)*1.0 / (SELECT sum(product_sales_order.total_price) AS month_nmv
FROM product_sales_order
WHERE product_sales_order.created_at::Date BETWEEN '{start}' AND '{end}'
AND product_sales_order.purchased_item_count <> 0)) AS contribution,
sum(product_sales_order.purchased_item_count * product_sales_order.basic_unit_count) AS bskt_size,
sum(product_sales_order.total_price)*1.0 / count(DISTINCT product_sales_order.sales_order_id) AS avg_ts,
sum(product_sales_order.total_price)*1.0 / count(DISTINCT sales_orders.retailer_id) AS nmv_p_retailer
FROM product_sales_order
LEFT JOIN sales_orders ON sales_orders.id = product_sales_order.sales_order_id
LEFT JOIN products ON products.id = product_sales_order.product_id
LEFT JOIN retailers on retailers.id = sales_orders.retailer_id
WHERE product_sales_order.created_at::date BETWEEN '{start}' AND '{end}'
GROUP BY 1,2
ORDER BY product_sales_order.product_id, product_sales_order.packing_unit_id, orders_count
) as kpis
LEFT JOIN (
SELECT performance.lost_revenue.product_id,
sum(performance.lost_revenue.lost_revenue) as lr
FROM performance.lost_revenue
WHERE performance.lost_revenue.created_at::Date between '{start}' AND '{end}'
GROUP BY 1
)as lr on lr.product_id = kpis.product_id
What could be corrected regarding the structure of the 2nd SQL query to make it yield the same results for orders_count?
Why does different values count return different results every run?

Make sum of num_importe by the entidad code sql

My code:
select distinct entidad, sum(cast(num_importe as float))
from envio_remesa
inner join remesa
on envio_remesa.id = remesa.envio_remesa_id
where remesa.envio_remesa_id = 3 and remesa.tipo_doc='201';
The case is that for example I have two different "entidades"(suppose 18 and 21, but it can be any number), and I want to group in two different records the sum of the "num_importe" for the "entidad" 18, and the sum of the "num_importe" for the "entidad" 21.How could I do it?
What I want to come out:
entidad num_importe
18 92.300,00
21 56.000,20
432 120.000,32
12 12.232,12
you shoud use group by (by the way, distinct is useless here)
select entidad, sum(cast(num_importe as float))
from envio_remesa
inner join remesa
on envio_remesa.id = remesa.envio_remesa_id
where remesa.envio_remesa_id = 3 and remesa.tipo_doc='201'
group by entidad;
You can use aggregation:
select entidad, sum(cast(num_importe as float))
from envio_remesa er inner join
remesa r
on er.id = r.envio_remesa_id
where r.envio_remesa_id = 3 and r.tipo_doc = '201'
group by entidad;
Note: You should qualify entidad and num_importe so it is clear what table they come from.
Also, I added table aliases into the query. They make the query easier to write and to read.

How to use 1 SQL query related to date and time in order to compare value difference

SELECT c.treatment_category, a.treatment_id, MAX(a.counts - b.counts) AS ReviewDifference
FROM
(SELECT treatment_id, COUNT(treatment_id) AS counts
FROM review
WHERE DATE(review.created) BETWEEN DATE(TIMESTAMP'2016-01-01 00:00:00.0') AND DATE(TIMESTAMP'2016-12-31 23:59:59.999')
GROUP BY treatment_id) a
LEFT JOIN
(SELECT treatment_id, COUNT(treatment_id)
FROM review
WHERE DATE(review.created) BETWEEN DATE(TIMESTAMP'2015-01-01 00:00:00.0') AND DATE(TIMESTAMP'2015-12-31 23:59:59.999')
GROUP BY treatment_id) b
ON a = b
LEFT JOIN
(SELECT t.treatment_category AS category, r.treatment_id AS number
FROM treatment t
LEFT JOIN review r
ON t.treatment_id = r.treatment_id
GROUP BY category, number) c
ON b.treatment_id = c.number
GROUP BY a.treatment_id, c.treatment_category
ORDER BY ReviewDifference DESC
LIMIT 1;
I need some hints or simpler query on how to do this question since it is related to date and time. Thank you.
What treatment category has seen the biggest increase in reviews from 2015 to 2016?
Please see below for the tables.
I have provided my code snippet and I would like to find a simpler and cleaner way on writing the code.
SELECT t.treatment_id, t.treatment_name,
COUNT( CASE WHEN YEAR(created) = 2016 THEN r.review_id END)
- COUNT( CASE WHEN YEAR(created) = 2015 THEN r.review_id END) as review_count
FROM treatments t
JOIN reviews r
ON t.treatment_id = r.treatment_id
GROUP BY t.treatment_id, t.treatment_name,
ORDER BY review_count DESC

Join & Subquery to calculate Minimum datediff

I have 2 SQL tables, one for subscribers (ID, Name), second for subscribers_Upgrades [Subscriber_ID (FK), Upgrade_Level, Upgrade_Date)
(There are 7 upgrade levels)
I need a query to get the top 10 subscribers who upgraded in the shortest period and Upgrade_Level, and Upgrade Date for specific Upgrade_Level (any one of the available 7 Upgrade level), and within specific period of time
We can, for example supply the 2 conditions like
Where Upgrade_Level = 3 and Upgrade_Date between '01-April-2014' and '20-May-2016'
What you mean shortest period? Who have upgraded in earliest time in upgrade_date order?
SELECT TOP 10 s.ID,
s.Name,
su.UpgradeLevel,
su.UpgradeDate
FROM Subscribers s
INNER JOIN SubscribersUpgrades su on s.ID = su.SubscriberId
WHERE su.UpgradeLevel = 3 AND su.UpgradeDate BETWEEN '01-April-2014' AND '20-May-2016'
ORDER BY su.UpgradeDate ASC
UPDATE
If you need data only for 2 upgrade level (level 2 and 3) this should work -
SELECT TOP 10 s.Name, DATEDIFF(dd,t1.UpgradeDate,t2.UpgradeDate) UpgradePeriodInDays FROM
(SELECT su.SubscriberId, su.UpgradeDate FROM SubscribersUpgrades su
WHERE su.UpgradeLevel = 2 ) t1
INNER JOIN (SELECT su.SubscriberId, su.UpgradeDate FROM SubscribersUpgrades su
WHERE su.UpgradeLevel = 3) t2 on t1.SubscriberId = t2.SubscriberId
INNER JOIN Subscribers s on t1.SubscriberId = s.ID
WHERE t2.UpgradeDate BETWEEN '01-June-2016' AND '20-July-2016'
ORDER BY DATEDIFF(dd,t1.UpgradeDate,t2.UpgradeDate) ASC

Group on two columns and calculate net total SQL Query

I am finding it difficult to modify an existing SQL query to group records on two columns. Following is the query which retrieves records from multiple tables by joining:
SELECT
InM.invm_No AS DocNo,
InM.docs_DocCode,
D.doctyp_Desc AS DocType,
L.loc_Desc AS Site,
InM.sup_Code AS Supplier,
InD.invd_Qty,
InD.invd_Rate
FROM
[SI_InventoryMaster] InM
INNER JOIN
[SI_DocType] AS D ON InM.doctyp_Code = D.doctyp_Code
INNER JOIN
SI_Supplier S ON InM.sup_Code = S.sup_Code
INNER JOIN
[SI_InventoryDetail] AS InD ON InD.invm_No = InM.invm_No
AND InM.invm_verified = 1
AND InM.docs_DocCode = 'GRN'
AND MONTH (InM.invm_Date) = 12
AND YEAR(InM.invm_date) = 2013
INNER JOIN
SI_Location L ON InD.loc_code = L.loc_Code
ORDER BY
InM.invm_No
Which results the following:
I need to group records "by DocNo by Site" and find total amount for each site. Total amount will be last column in this resultset and it is net of product of InD.invd_Qty and InD.invd_Rate for each site.
For DocNo: 00000030, there are 4 records of CWS Store Site, so its total amount would be calculated as: 7684.999+7684.999+3000+3000=21369.998
In this particular example, modified query should return following resultset:
Please help.
Thanks.
Try grouping on all the columns associated with those two columns. Something like:
SELECT InM.invm_No AS DocNo, InM.docs_DocCode, D.doctyp_Desc AS DocType,
L.loc_Desc AS Site, InM.sup_Code AS Supplier,
sum(InD.invd_Qty),
sum(InD.invd_Rate)
FROM [SI_InventoryMaster] InM INNER JOIN
[SI_DocType] AS D
ON InM.doctyp_Code = D.doctyp_Code INNER JOIN
SI_Supplier S
ON InM.sup_Code = S.sup_Code INNER JOIN
[SI_InventoryDetail] AS InD
ON InD.invm_No = InM.invm_No AND
InM.invm_verified = 1 AND
InM.docs_DocCode = 'GRN' AND
MONTH (InM.invm_Date) = 12 AND
YEAR(InM.invm_date) = 2013 INNER JOIN
SI_Location L
ON InD.loc_code = L.loc_Code
GROUP BY InM.invm_No AS DocNo, InM.docs_DocCode, D.doctyp_Desc AS DocType,
L.loc_Desc AS Site, InM.sup_Code AS Supplier;