I am trying to create a web based report to show the response of certain advertisements.
$sql1 = "
SELECT date
, source
, source_desc
, COUNT(ordernumber) count
, SUM(ordervalue) value
, type
FROM dailystats
WHERE client = '$client2'
AND event <> 'B02'
AND date BETWEEN '$start' AND '$end'
GROUP
BY source
ORDER
BY source;
";
This works fine for my table to show total values, but I want to break it down further. I currently have SOURCE {source}, DESCRIPTION {source_desc}, TOTAL ORDERS {count}, TOTAL ORDER VALUE {value}, as my headers which are populated by the above fields.
I want, as well as the current totals, to include further columns when the field "TYPE" is "P", "T" and "E". I want this to leave me with data to fill new headers (when I put them into the table) consisting of SOURCE, DESCRIPTION, WEB ORDERS, WEB ORDER VALUE, PHONE ORDERS, PHONE ORDER VALUE, POST ORDERS, POST ORDER VALUE, TOTAL ORDERS, TOTAL ORDER VALUE.
I need to create the data for the new headers, so WEB ORDERS will give me the total orders with the TYPE "E". On its own this would be something like COUNT(ordernumber) count where type = "E", but I need multiple of these and I cannot get it to work.
It currently looks like this :
|Source|Source Description|Total Orders|Total Order Value|
|DM1 |Daily Mail 1 |500 |5,000 |
I want to retain this information, but add in as described above, to look like this.
|Source|Source Description|Web Orders|Web Order Value|Post Orders|Post Order Value|Mail Orders|Mail Order Value|Total Orders|Total Order Value|
|DM1 |Daily Mail 1 |100 |1,000 |300 |3,000 |100 |1,000 |500 |5,000 |
I hope I have explained my problem adequately.
use group_concat(type) as type in your code.
(if it is wrong sry. pls explain it clear)
I want this to leave me with headers (when I put them into the table) of SOURCE, DESCRIPTION, WEB ORDERS, WEB ORDER VALUE, PHONE ORDERS, PHONE ORDER VALUE, POST ORDERS, POST ORDER VALUE, TOTAL ORDERS, TOTAL ORDER VALUE.
If i understand correctly you want to add headers to your result ? this should be done by:
SELECT column_name(s)
FROM table_name AS alias_name;
Related
I will explain the logic:
I need to retrieve only the most recent room type/rate plan combinations from the rateplan_roomtypeTable.
room type ID and rate plan id are located in separate columns
there are 2 conditions that need to be met: all active room type/rate plan combinations need to be retrieved along with all room type/rate plan combinations that have produced even if they are not active. All these combinations need to be the most recent ones.
The desired results would be like the table I ll share with you:
Your help with the below query will be much appreciated:
select
Id
, RoomTypeId
, RateTypeId
,isactiveRateType
,isactiveRoomType
, RatePlanName
, RoomTypeName
FROM
rateplan_roomtypeTable
where
RateTypeId IN (select RateTypeId from ProductionTable where (cast(bookingdate as date) between date_add('day',-92, current_date) and date_add('day', -2, current_date)))
OR (isactiveRateType = 1 and isactiveRoomType = 1)
GROUP BY
1,2,3,4,5
Thank you
I have a database with a table called 'messages'. The colums are 'sender', 'reseiver', 'subject', 'time' (the timestamp).
With my query, I want to get the entries grouped by the subject. BUT I want to have the corresponding time to be the latest.
So, for example, if this was my db:
person1 | person2 | hello | 2019-06-24 20:0**7**:00
person2 | person1 | hello | 2019-06-24 20:0**8**:00
I want to get this:
subject: hello
last entry: 2019-06-24 20:0**8**:00
I wasn't able to put the ORDER BY in front of the GROUP BY, so I tried a subquery:
SELECT subject, sender, receiver, time
FROM
(SELECT subject, sender, receiver, time
FROM messages
ORDER BY time DESC) AS subselect
GROUP BY subject
But it doesn't work and I can't figure out why.
Can somebody help me?
SELECT subject,sender,reseiver,max(time)
FROM messages
GROUP BY subject,sender,reseiver
ORDER BY max(time) DESC
You should group by sender,reseiver as well, otherwise those columns have unpredictable value. Or omit those column entirely.
I believe this is what you are looking for:
SELECT subject,sender,reseiver, MAX(time) AS time FROM messages GROUP BY subject
So, it works like this:
Gets relevant records (in this case -- all of them, as no WHERE provided)
Groups them by subject column, so now we have groups of records with the same subject
In every group it looks for max value of time column -- but this is per group, so, I guess that's what you wanted
And if you want to sort groups somehow, just add another ORDER BY at the end, without any subqueries.
I want a interactive sorting in SSRS matrix report. From database we are getting 3 columns -PrimaryKey,Columns and Value.
We are grouping rows by Primary Key and grouping column by Columns and use Value as data.
My Matrix Report -
ID [Columns]
[Primary Key] Values
Output of the Matrix report -
ID FirstName MiddleName Lastname
1 Rajiv Jha Sharma
2 Prem Kumar Bose
3 Usha Shamila Praveena
I am able to use the interactive sorting on ID because ID is group by rows but I want to use the interactive sorting on dynamic cloumns values like FirstName,MiddleName and LastName.
Expected result when we interactive sort on Lastname
ID FirstName MiddleName Lastname
2 Prem Kumar Bose
3 Usha Shamila Praveena
1 Rajiv Jha Sharma
Thanks for any Help.
Are you using the report wizard to build this? You should be able apply the interactive sort using the properties menu on the column groups.
By adding an interactive sort button to a column header you can allow a user to click the column header and sort the parent group rows in a table or matrix by the value displayed in that column. The order of child groups remains unchanged.
To add an interactive sort button to a column header to sort groups:
In a table or matrix on the report design surface, right-click the text box in the column header for the group to which you want to add an interactive sort button.
Click Text Box Properties.
Click Interactive Sort.
Select Enable interactive sort on this text box.
In Sort, click Groups.
From the drop-down list, select the name of the group that you are sorting. For groups based on simple group expressions, the Sort by value is populated with group expression.
For more info, see this article: http://technet.microsoft.com/en-us/library/cc627509(v=sql.100).aspx
Quite an old question, but I stumbled upon similar problem recently.
Though SSRS does not allow you to add interactive sorting on dynamic columns in a matrix, you can simulate similar behaviour. I've figured out a method, which require the report to fire itself (through go to report action) sorted on desired column.
I will use a bit more complicated example to show the full functionality of this solution.
Imagine an online bookstore, which would like a report showing their customers (rows), number of books (values) and total value of books (values), which they bought, by category – Fiction/NonFiction in my example (columns). Of course they want to see their best customers, so the sort will be descending.
Example data that we are getting from the database:
UserID Columns BooksCount BooksValue
AliBaba Fiction 2 25.96
AliBaba NonFiction 4 112.00
ThomasJefferson Fiction 3 36.83
ThomasJefferson NonFiction 1 46.80
BillCosby Fiction 10 536.47
BillCosby NonFiction 2 26.87
The report will look like this:
[Columns]
Books Count Books Value
[UserID] Values Values
I would like the report to be able to sort by “Books Count” or “Books Value” for any Column. Here are the steps to follow:
You need to add parameters that will store the name of the column to sort on - #SortColumn and the metric name (counts or values) to sort on - #SortMetric.
Go to “Books Count” textbox and add action "Go to report" specifying the same report. Add #SortColumn parameter with a value from [Columns] field in the underlying dataset. Add #SortMetric parameter with value set to “BooksCount”. Similar for “Books Value” textbox.
You can adjust the column header text with following expression, which will show the user on which column data is sorted:
= IIf( Parameters!SortColumn.Value=Fields!Columns.Value And Parameters!SortMetric.Value = "BooksCount" ," ^","")
This was for “Books Count”, you can add similar for “Books Amount”
Finally the magic that happens on the database site. Source table is named [Sales]. Apart from the sorting, below code allows to select only top N rows if your dataset is larger.
You can create a dataset using this code or better create a stored procedure. And join report parameters with dataset parameters.
DECLARE #TopN INT = 50
;WITH Users_Sorted AS
(
SELECT
UserID
,ROW_NUMBER() OVER (ORDER BY
CASE #SortMetric
WHEN 'BooksCount' THEN Sales.BooksCount
WHEN 'BooksValue' THEN Sales.BooksValue
END DESC) AS ROWNO
FROM Sales
WHERE
Sales.Columns = #SortColumn
)
,Sales_MAIN AS
(
SELECT
Sales.UserID
,Sales.Columns
,Sales.BooksCount
,Sales.BooksValue
,ISNULL(Users_Sorted.ROWNO,
ROW_NUMBER () OVER (PARTITION BY Sales.Columns ORDER BY Sales.UserID ASC)
) AS ROWNO
FROM Sales
LEFT JOIN Users_Sorted ON Sales.UserID = Users_Sorted.UserID
)
SELECT * FROM Sales_MAIN WHERE ROWNO <= #TopN ORDER BY ROWNO
I have a quick question that I can't seem to figure out. I'm trying to list end user items (just an example) with only the most recent comment displayed.
ID Name EventDate Type
1 PC 12/12/2012 End User Items
1 PC 11/12/2012 End User Items
1 PC 10/11/2012 End User Items
2 Mobile 12/12/2012 End User Items
2 Mobile 11/01/2012 End User Items
2 Mobile 12/12/2011 End User Items
3 Server 12/12/2013 Server
So I would try something like this:
select * from systems where type = "End User Items" group by ID
But the result would still not show the latest date.
Any help would be greatly appreciated!
Have you tried getting the MAX date as follows?
SELECT Name,
MAX(EventDate),
Type
FROM systems
WHERE type = 'End User Items'
GROUP BY Name, Type
You can use a subQuery to get the ID and MAX Date and then join back on your systems table with the ID and the MAX date.
SELECT s2.Name, s.EventDate
FROM system s2
INNER JOIN (SELECT ID, MAX(EventDate) EventDate
FROM systems
WHERE type = 'End User Items'
GROUP BY ID) AS s on s2.ID = s.ID AND s2.EventDate = s.EventDate
Define the columns you want to show without summarization as your GROUP BY fields. Select those fields and the calculated summary function columns (eg. max(), sum(), count() ).
SELECT ID, Name, MAX(EventDate) as LastDate
FROM systems
WHERE type = 'End User Items'
GROUP BY ID, Name
You probably want to see ID, and Name. Type is superfluous here, since you only want one Type. You want to get the max() date in the group. All fields returned must either be summary functions, or GROUP BY columns.
I've currently got a table as follows,
Column Type
time datetime
ticket int(20)
agentid int(20)
ExitStatus varchar(50)
Queue varchar(50)
I want to write a query which will break this down by week, providing a column with a count for each ExitStatus. So far I have this,
SELECT ExitStatus,COUNT(ExitStatus) AS ExitStatusCount, DAY(time) AS TimePeriod
FROM `table`
GROUP BY TimePeriod, ExitStatus
Output:
ExitStatus ExitStatusCount TimePeriod
NoAgentID 1 4
Success 3 4
NoAgentID 1 5
Success 5 5
I want to change this so it returns results in this format:
week | COUNT(NoAgentID) | COUNT(Success) |
Ideally, I'd like the columns to be dynamic as other ExitStatus values may be possible.
This information will be formatted and presented to end user in a table on a page. Can this be done in SQL or should I reformat it in PHP?
There is no "general" solution to your problem (called cross tabulation) that can be achieved with a single query. There are four possible solutions:
Hardcode all possible ExitStatus'es in your query and keep it updated as you see the need for more and more of them. For example:
SELECT
Day(Time) AS TimePeriod,
SUM(IF(ExitStatus = 'NoAgentID', 1, 0)) AS NoAgentID,
SUM(IF(ExitStatus = 'Success', 1, 0)) AS Success
-- #TODO: Add others here when/if needed
FROM table
WHERE ...
GROUP BY TimePeriod
Do a first query to get all possible ExitStatus'es and then create your final query from your high-level programming language based on those results.
Use a special module for cross tabulation on your high-level programming language. For Perl, you have the SQLCrossTab module but I couldn't find one for PHP
Add another layer to your application by using OLAP (multi-dimensional views of your data) like Pentaho and then querying that layer instead of your original data
You can read a lot more about these solutions and an overall discussion of the subject
This is one way; you can use SUM() to count the number of items a particular condition is true. At the end you just group by the time as per normal.
SELECT DAY(time) AS TimePeriod,
SUM('NoAgentID' = exitStatus) AS NoAgentID,
SUM('Success' = exitStatus) AS Success, ...
FROM `table`
GROUP BY TimePeriod
Output:
4 1 3
5 1 5
The columns here are not dynamic though, which means you have to add conditions as you go along.
SELECT week(time) AS week,
SUM(ExitStatus = 'NoAgentID') AS 'COUNT(NoAgentID)',
SUM(ExitStatus = 'Success') AS 'COUNT(Success)'
FROM `table`
GROUP BY week
I'm making some guesses about how ExitStatus column works. Also, there are many ways of interpretting "week", such as week of year, of month, or quarter, ... You will need to put the appropriate function there.