Sql GroupBy with one more field in the result set as in the group by clause - tsql

I have a table with different offers which are bound to a specific date. depended on the date the price changes. i want to get the cheapest deal for each date.
my problem is i use a group by like:
select price, date from deals group by date, price
to display the offer, i need more records which are not in the group by clause. the best field would be my autoid, so if a customer selects a offer with a specific price i can display this offer with all its fields using a second select.
i hope this makes it simpler to answer my question. i tried to keep it generic as possible but i have the feeling it was not described clear enough :-)

Just add the Id column into the GROUP BY list
SELECT id, date, price
FROM products
GROUP BY id, date, price
Otherwise Sql Server was not able identify which id is to return for grouped by price and date rows, for instance consider two following rows:
1 | 10-10-2010 | 100 |
2 | 10-10-2010 | 100 |
Which Id value should be selected for row which is grouped by date and price?
??? | 10-10-2010 | 100 |

You either need to specify an aggregate function on ID or add it to your group by clause like #sll suggested. Aggregate example:
SELECT MAX(id), date, price
FROM products
GROUP BY date, price

If you remove the id from Select clause, you will have a list of all distinct couples of date and price.
If you add the id to the Group By clause, since it is an identity, you will obtain a row per every record in your table, so that your Group By clause won't be useful.
The third way is to use an aggregate function on id in the Select clause to obtain one value for every single group (the first, the min, the max, etc.).

Hi Group by is useful when you are doing count etc.
SELECT [Display Billing Provider], [Display Insurance Category]
, SUM([TOTAL RVUs]) AS RVUs_08
, SUM([Units]) AS Units_08
, SUM(Payments) AS Payments_08
FROM dbo.ProductivityAnal_2008
GROUP BY [Display Billing Provider],[Display Insurance Category]
ORDER BY [Display Billing Provider],[Display Insurance Category]
Thanks Abe

Related

count distinct idi_counterparty PER campaignId tableau

it's my first time here, I have a question I can't solve.
I need a calculation that allows me to see the amount of id there is per campaignid
count distinct idi_counterparty PER campaignId.
Should take into account all activities (sent/open/click)
both columns contain numbers (because they are id)

How to select max date value while selecting max value

I have the following sample from a table with students results with date for a school entry exam
First student passed exam - This is the most common record found for most students
Second student failed 1st time entry and passed second time based on the date
3rd student had a failed input entry and was corrected based on the Version
I need the results to like like the picture above, so we take into regard using the latest date and highest version!
My basic query thus far is
select studentid
,examdate --(Date)
,result -- (charvar)
from StudentEntryExam
How should I approach this issue?
demo:db<>fiddle
SELECT DISTINCT ON (studentid)
*
FROM mytable
ORDER BY studentid, examdate DESC, version DESC
DISTINCT ON returns the first record of an ordered group. In that case the groups are the studentids. You must find the correct order to set the required record first. So, you need to order by studentid, of course. Then you need the most recent examdate first, which can be achieved with DESC order. If there are two records on the same date, you need to order the highest version first as well using the DESC modifier, too.

how to put condition users on tableau

im mysql user, i have data source like this
User_id | Order_id | Status_id | createdAt | Transaction_Amount
user_id as the user, order_id as the id of the order, status_id as the status of each order, createdAt as the date of the transaction .
in MySQL, i divide the condition of the users in 4 conditions.
conditions 1 new_user
the user who doing FIRST transaction in date range, and not doing transaction before the date range
conditions 2 repeat_user
the user who doing transaction before the end of date range, and doing atleast 1 more transactions in date range
conditions 3 existing_user
the user who doing his first transaction before the date range, and doing atleast 1 more transactions in date range
conditions 4 unique_user
the user who doing transaction in date range
i've done it with the queries in mysql, but i want to visualize it in tableau, i already make the filter of the time range, but how to make the conditions to based on condition user
Assuming that you want to have create these conditions in tableau, I propose a solution like this. Since you've not provided any data to work upon, a data I used in excel is as
View-1 add a Calculated field(CF) First Transaction of User as
{FIXED [user_id]: MIN([CreatedAt])}
Drag this field on filter instead of created at and you'll get a view based on your condition_1. Screenshot
View-2 (I am assuming that both transactions may have been completed within the filtered date range. If you need otherwise please specify).
step-1. drag user_id to rows, createdAt at filters (select range of dates).
Step-2 Drag order_id to filters again select count distinct, select at least 2
You'll get a view like this
View-3 Add two CFs as. 1st condition 1 as
Min([First Transaction of User])< min([CreatedAt])
another CF condition 3 check2 as
{Fixed [user_id]: COUNTD([order_id])}>1
Add both these CFs on filter shelf along with createdAt. Add condition-1 check2 to context (important step) select TRUE from both filters and you'll get desired view. like this
View-4 It is the most basic chart in tableau. Try and I am sure you can do it. Good luck
From your workbook it is clear that you want cohort analysis. In this regard Let me explain a few things..
First create a user cohort like this
{FIXED [user_id]: MIN([CreatedAt])}
Output of this field will be date when user first ordered. So if you will add this field to filters the output will be users (added in view) who first ordered within the filtered date/range.
Now if you want to see the users' orders during the same period (condition 1) also add the createdAt field to filters with same date/range.
E.g. suppose your date range is 5jan to 15 jan. Then set both filters to these dates range. First filter will ensure to filter customer with their first transaction and second one will give you desired output.
For condition2, you'll have to add countd(order_ids) to filters with filter value set 'at least 2'.
E.g. setting this filter will ensure that customer did their first and at least one more transaction during the date range.
For condition3, changing dates in filter accordingly will do. Nothing extra to be done.
E.g. suppose you want the customers with second and onward transaction between 5 jan to 15 jan. Then you will have to set first cohort filter with date upto 4 jan but second date filter to 5 jan to 15 jan
Condition 4: remove cohort from filters. Set date range on createdAt field only.
If you want to add another filters like status etc., These will work after you add them to filters.
Try this

How to sort by a calculated column in PostgreSQL?

We have a number of fields in our offers table that determine an offer's price, however one crucial component for the price is an exchange rate fetched from an external API. We still need to sort offers by actual current price.
For example, let's say we have two columns in the offers table: exchange and premium_percentage. The exchange is the name of the source for the exchange rate to which an external request will be made. premium_percentage is set by the user. In this situation, it is impossible to sort offers by current price without knowing the exchange rate, and that maybe different depending on what's in the exchange column.
How would one go about this? Is there a way to make Postgres calculate current price and then sort offers by it?
SELECT
product_id,
get_current_price(exchange) * (premium_percentage::float/100 + 1) AS price
FROM offers
ORDER BY 2;
Note the ORDER BY 2 to sort by the second ordinal column.
You can instead repeat the expression you want to sort by in the ORDER BY clause. But that can result in multiple evaluation.
Or you can wrap it all in a subquery so you can name the output columns and refer to them in other clauses.
SELECT product_id, price
FROM
(
SELECT
product_id,
get_current_price(exchange) * (premium_percentage::float/100 + 1)
FROM offers
) product_prices(product_id, price)
ORDER BY price;

Crystal Reports Filter by Most Recent Date of Field

I have a report I am creating through an ODBC connection. The report includes several invoices, where each invoice has several products. There is also a table which contains all the historical price changes for each product (field: unit-price). Currently there are duplicate product records being pulled, one for each time there was a price change. Therefore, I need to filter my data so that only the most recent unit-price is shown (date field: effective-date). How can I do this via the "Select Expert?"
In short, show the product's unit-price for the most recent effective-date.
Thank you!
You'll need to create a sql-expression field to get the most-recent effective date, then use this field in the record-selection formula.
// {%MAX_EFFECTIVE_DATE}
// most-likely you'll need to alias the table in the main report for this to work
(
SELECT Max(effective_date)
FROM price_history
WHERE product_id = price_history_alias.product_id
)
Record-selection formula:
{price_history_alias.effective_date}={%MAX_EFFECTIVE_DATE}
Instead of doing it in select expert. group by effective date and set the ordering as Descending.